diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 000000000..cc9f69b8b --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,159 @@ +name: Build + +on: [push, pull_request] + +jobs: + build-cmake: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macOS-latest, windows-latest, ubuntu-18.04] + include: + - os: ubuntu-latest + cmake-args: -G "Unix Makefiles" + build-args: --parallel + package-file: teeworlds-*-linux_x86_64.tar.xz + env: + CFLAGS: -Wdeclaration-after-statement -Werror + CXXFLAGS: -Werror + - os: ubuntu-18.04 + cmake-path: /usr/bin/ + cmake-args: -G "Unix Makefiles" + package-file: teeworlds-*-linux_x86_64.tar.xz + env: + CFLAGS: -Wdeclaration-after-statement -Werror + CXXFLAGS: -Werror + - os: macOS-latest + cmake-args: -G "Unix Makefiles" + build-args: --parallel + package-file: teeworlds-*-osx.dmg + env: + CFLAGS: -Wdeclaration-after-statement -Werror + CXXFLAGS: -Werror + - os: windows-latest + cmake-args: -A x64 + package-file: teeworlds-*-win64.zip + env: + CFLAGS: /WX + CXXFLAGS: /WX + LDFLAGS: /WX + + steps: + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Prepare Linux + if: contains(matrix.os, 'ubuntu') + run: | + sudo apt-get update -y + sudo apt-get install pkg-config cmake libfreetype6-dev libsdl2-dev -y + + - name: Prepare MacOS + if: contains(matrix.os, 'macOS') + run: | + brew update + brew install pkg-config sdl2 + + - name: Build in debug mode + env: ${{ matrix.env }} + run: | + mkdir debug + cd debug + ${{ matrix.cmake-path }}cmake --version + ${{ matrix.cmake-path }}cmake ${{ matrix.cmake-args }} -DCMAKE_BUILD_TYPE=Debug -Werror=dev -DDOWNLOAD_GTEST=ON -DDEV=ON -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG=. .. + ${{ matrix.cmake-path }}cmake --build . --config Debug ${{ matrix.build-args }} --target everything + - name: Test debug + run: | + cd debug + ${{ matrix.cmake-path }}cmake --build . --config Debug ${{ matrix.build-args }} --target run_tests + - name: Run debug server + env: ${{ matrix.env }} + run: | + cd debug + ./teeworlds_srv shutdown + + - name: Build in release mode + env: ${{ matrix.env }} + run: | + mkdir release + cd release + ${{ matrix.cmake-path }}cmake ${{ matrix.cmake-args }} -DCMAKE_BUILD_TYPE=Release -Werror=dev -DDOWNLOAD_GTEST=ON -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE=. .. + ${{ matrix.cmake-path }}cmake --build . --config Release ${{ matrix.build-args }} --target everything + - name: Test release + run: | + cd release + ${{ matrix.cmake-path }}cmake --build . --config Release ${{ matrix.build-args }} --target run_tests + - name: Run release server + env: ${{ matrix.env }} + run: | + cd release + ./teeworlds_srv shutdown + + - name: Package + run: | + cd release + ${{ matrix.cmake-path }}cmake --build . --config Release ${{ matrix.build-args }} --target package_default + mkdir artifacts + mv ${{ matrix.package-file }} artifacts + + - name: Upload Artifacts + uses: actions/upload-artifact@v1 + with: + name: teeworlds-${{ matrix.os }} + path: release/artifacts + + build-bam: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macOS-latest, windows-latest] + + steps: + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Checkout bam + uses: actions/checkout@v2 + with: + repository: matricks/bam + ref: 8cd08744c37666830d439ab54016c9d228c63b68 + path: ./bam + + - name: Prepare Linux + if: contains(matrix.os, 'ubuntu') + run: | + sudo apt-get update -y + sudo apt-get install libfreetype6-dev libsdl2-dev -y + cd bam + ./make_unix.sh + + - name: Prepare MacOS + if: contains(matrix.os, 'macOS') + run: | + brew update + brew install sdl2 + cd bam + ./make_unix.sh + + - name: Prepare Windows + if: contains(matrix.os, 'windows') + run: | + cd bam + ./make_win64_msvc.bat + + - name: Build in debug mode + run: ./bam/bam conf=debug all + - name: Test debug + run: ./build/x86_64/debug/teeworlds_srv shutdown + + - name: Build in release mode + run: ./bam/bam conf=release all + - name: Test release + run: ./build/x86_64/release/teeworlds_srv shutdown + + - name: Create MacOS app using make_release.py + if: contains(matrix.os, 'macOS') + run: | + sudo python3 scripts/make_release.py master osx diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml new file mode 100644 index 000000000..ab0d04d87 --- /dev/null +++ b/.github/workflows/style.yml @@ -0,0 +1,31 @@ +name: Check style + +on: + push: + branches-ignore: + - master + - staging.tmp + - trying.tmp + - staging-squash-merge.tmp + pull_request: + +jobs: + check-style: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + with: + submodules: true + - name: Prepare + run: | + sudo apt-get update -y + sudo apt-get install jq -y + - name: Check header guards + run: scripts/check_header_guards.py + - name: Lint JSON + run: | + while read -r json; + do + jq '.' "$json" || { echo "$json"; exit 1; }; + done < <(find . -name "*.json"); + diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..15fcddd96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,77 @@ +/.bam +/bam +/build +/config.lua +/objs +/other/*/include +/other/*/lib +/other/*/linux +/other/*/mac +/other/*/windows +__pycache__/ +*.dll +*.dmg +*.pyc +*.pyo +scripts/work/ +/SDL.dll +/freetype.dll +/autoexec.cfg +other/freetype +other/sdl +Info.plist + +crapnet* +fake_server* +map_resave* +map_version* +mastersrv* +packetgen* +teeworlds* +!other/bash-completion/teeworlds +!teeworlds.manifest +!teeworlds.rc +teeworlds_srv* +!other/bash-completion/teeworlds_srv +testrunner +versionsrv* + +# IDE project files +.cproject +.idea +.project +.settings +.vs +.vscode +*.vcxproj +*.vcxproj.filters +compile_commands.json +cscope.files +cscope.out +out +tags + +# CMake +data +generated + +.ninja_deps +.ninja_log +CMakeCache.txt +CMakeFiles +CMakeSettings* +CPackConfig.cmake +CPackSourceConfig.cmake +Debug +Makefile +RelWithDebInfo +Release +_CPack_Packages/ +build.ninja +cmake_install.cmake +googletest-build +googletest-download +googletest-src +install_manifest.txt +pack_*/ +rules.ninja diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..e2905a89d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,8 @@ +[submodule "datasrc/languages"] + path = datasrc/languages + url = https://github.com/teeworlds/teeworlds-translation.git + branch = master +[submodule "datasrc/maps"] + path = datasrc/maps + url = https://github.com/teeworlds/teeworlds-maps.git + branch = master diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..51ba9664f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,2157 @@ +cmake_minimum_required(VERSION 2.8.12...3.19.1) +if(CMAKE_VERSION VERSION_LESS 3.12) + cmake_policy(VERSION ${CMAKE_VERSION}) +endif() + +file(STRINGS src/game/version.h VERSION_LINE + LIMIT_COUNT 1 + REGEX GAME_RELEASE_VERSION +) + +if(VERSION_LINE MATCHES "\"([0-9]+)\\.([0-9]+)\\.([0-9]+|[0-9]+\\.[0-9]+)\"") + set(VERSION_MAJOR ${CMAKE_MATCH_1}) + set(VERSION_MINOR ${CMAKE_MATCH_2}) + set(VERSION_PATCH ${CMAKE_MATCH_3}) +elseif(VERSION_LINE MATCHES "\"([0-9]+)\\.([0-9]+)\"") + set(VERSION_MAJOR ${CMAKE_MATCH_1}) + set(VERSION_MINOR ${CMAKE_MATCH_2}) + set(VERSION_PATCH "0") +else() + message(FATAL_ERROR "Couldn't parse version from src/game/version.h") +endif() + +# Extra support for CMake pre-3.0 +if(NOT POLICY CMP0048) + set(PROJECT_VERSION_MAJOR ${VERSION_MAJOR}) + set(PROJECT_VERSION_MINOR ${VERSION_MINOR}) + set(PROJECT_VERSION_PATCH ${VERSION_PATCH}) + set(PROJECT_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) +endif() + +project(teeworlds VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) + +set(ORIGINAL_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +set(ORIGINAL_CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES}) +set(ORIGINAL_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) +set(OWN_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/cmake) +set(CMAKE_MODULE_PATH ${OWN_CMAKE_MODULE_PATH}) + +if(CMAKE_SIZEOF_VOID_P EQUAL 4) + set(TARGET_BITS "32") +else() + set(TARGET_BITS "64") +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Windows") + set(TARGET_OS "windows") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(TARGET_OS "linux") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(TARGET_OS "mac") +endif() + +include(CheckCCompilerFlag) +include(CheckCXXCompilerFlag) +include(CheckSymbolExists) + +check_symbol_exists(__i386 "" TARGET_ARCH_X86_i386) +if(TARGET_ARCH_X86_i386) + set(TARGET_ARCH x86) +else() + set(TARGET_ARCH) +endif() + +set(AUTO_DEPENDENCIES_DEFAULT OFF) +if(TARGET_OS STREQUAL "windows") + set(AUTO_DEPENDENCIES_DEFAULT ON) +endif() + +option(CLIENT "Compile client" ON) +option(HEADLESS_CLIENT "Build the client without graphics" OFF) +option(DOWNLOAD_DEPENDENCIES "Download dependencies (only available on Windows)" ${AUTO_DEPENDENCIES_DEFAULT}) +option(DOWNLOAD_GTEST "Download and compile GTest if not found" ${AUTO_DEPENDENCIES_DEFAULT}) +option(PREFER_BUNDLED_LIBS "Prefer bundled libraries over system libraries" ${AUTO_DEPENDENCIES_DEFAULT}) +option(DEV "Don't generate stuff necessary for packaging" OFF) + +set(OpenGL_GL_PREFERENCE GLVND) + +# Set the default build type to Release +if(NOT(CMAKE_BUILD_TYPE)) + if(NOT(DEV)) + set(CMAKE_BUILD_TYPE Release) + else() + set(CMAKE_BUILD_TYPE Debug) + endif() +endif() + +set(DBG $,$>) + +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + src/game/version.h +) + +set(SERVER_EXECUTABLE teeworlds_srv CACHE STRING "Name of the built server executable") +set(CLIENT_EXECUTABLE teeworlds CACHE STRING "Name of the build client executable") + +######################################################################## +# Download dependencies +######################################################################## + +find_package(PythonInterp) +if(DOWNLOAD_DEPENDENCIES) + if(PYTHON_EXECUTABLE AND TARGET_OS STREQUAL "windows" AND TARGET_BITS) + set(DOWNLOADS) + foreach(d freetype sdl) + if(NOT EXISTS "${PROJECT_SOURCE_DIR}/other/${d}/${TARGET_OS}/lib${TARGET_BITS}") + list(APPEND DOWNLOADS ${d}) + endif() + endforeach() + if(DOWNLOADS) + message(STATUS "Downloading Freetype and SDL 2") + execute_process(COMMAND ${PYTHON_EXECUTABLE} scripts/download.py ${DOWNLOADS} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) + endif() + endif() +endif() + +######################################################################## +# Compiler flags +######################################################################## + +function(add_c_compiler_flag_if_supported VARIABLE FLAG) + if(ARGC GREATER 2) + set(CHECKED_FLAG "${ARGV2}") + else() + set(CHECKED_FLAG "${FLAG}") + endif() + string(REGEX REPLACE "[^A-Za-z0-9]" "_" CONFIG_VARIABLE "FLAG_SUPPORTED${CHECKED_FLAG}") + check_c_compiler_flag("${CHECKED_FLAG}" ${CONFIG_VARIABLE}) + if(${CONFIG_VARIABLE}) + if(${VARIABLE}) + set("${VARIABLE}" "${${VARIABLE}};${FLAG}" PARENT_SCOPE) + else() + set("${VARIABLE}" "${FLAG}" PARENT_SCOPE) + endif() + endif() +endfunction() + +if(NOT MSVC) + # Protect the stack pointer. + # -fstack-protector-all doesn't work on MinGW. + add_c_compiler_flag_if_supported(OUR_FLAGS -fstack-protector-strong) + + # Protect the stack from clashing. + add_c_compiler_flag_if_supported(OUR_FLAGS -fstack-clash-protection) + + # Control-flow protection. Should protect against ROP. + add_c_compiler_flag_if_supported(OUR_FLAGS -fcf-protection) + + # Inaccurate floating point numbers cause problems on mingw-w64-gcc when + # compiling for x86, might cause problems elsewhere. So don't store floats + # in registers but keep them at higher accuracy. + if(TARGET_ARCH STREQUAL "x86") + add_c_compiler_flag_if_supported(OUR_FLAGS -ffloat-store) + endif() + + # gcc < 4.10 chokes on _mm_pause on x86 without SSE support. + if(TARGET_ARCH STREQUAL "x86") + check_c_source_compiles("#include \nint main() { _mm_pause(); return 0; }" MM_PAUSE_WORKS_WITHOUT_MSSE2) + if(NOT MM_PAUSE_WORKS_WITHOUT_MSSE2) + add_c_compiler_flag_if_supported(OUR_FLAGS -msse2) + endif() + endif() + + if(TARGET_OS STREQUAL "mac") + add_c_compiler_flag_if_supported(OUR_FLAGS -stdlib=libc++) + add_c_compiler_flag_if_supported(OUR_FLAGS -mmacosx-version-min=10.7) + endif() + + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN -Wall) + if(CMAKE_VERSION VERSION_GREATER 3.3 OR CMAKE_VERSION VERSION_EQUAL 3.3) + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN + $<$:-Wdeclaration-after-statement> + -Wdeclaration-after-statement + ) + endif() + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN -Wextra) + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN -Wno-unused-parameter) + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN -Wno-missing-field-initializers) + add_c_compiler_flag_if_supported(OUR_FLAGS_OWN -Wformat=2) # Warn about format strings. + add_c_compiler_flag_if_supported(OUR_FLAGS_DEP -Wno-implicit-function-declaration) +endif() + +if(NOT MSVC) + check_c_compiler_flag("-O2;-Wp,-Werror;-D_FORTIFY_SOURCE=2" DEFINE_FORTIFY_SOURCE) # Some distributions define _FORTIFY_SOURCE by themselves. +endif() + +######################################################################## +# COMMON FUNCTIONS +######################################################################## + +function(set_glob VAR GLOBBING EXTS DIRECTORY) # ... + set(GLOBS) + foreach(ext ${EXTS}) + list(APPEND GLOBS "${DIRECTORY}/*.${ext}") + endforeach() + file(${GLOBBING} GLOB_RESULT ${GLOBS}) + list(SORT GLOB_RESULT) + set(FILES) + foreach(file ${ARGN}) + list(APPEND FILES "${PROJECT_SOURCE_DIR}/${DIRECTORY}/${file}") + endforeach() + + if(NOT FILES STREQUAL GLOB_RESULT) + message(AUTHOR_WARNING "${VAR} does not contain every file from directory ${DIRECTORY}") + set(LIST_BUT_NOT_GLOB) + if(POLICY CMP0057) + cmake_policy(SET CMP0057 NEW) + foreach(file ${FILES}) + if(NOT file IN_LIST GLOB_RESULT) + list(APPEND LIST_BUT_NOT_GLOB ${file}) + endif() + endforeach() + if(LIST_BUT_NOT_GLOB) + message(AUTHOR_WARNING "Entries only present in ${VAR}: ${LIST_BUT_NOT_GLOB}") + endif() + set(GLOB_BUT_NOT_LIST) + foreach(file ${GLOB_RESULT}) + if(NOT file IN_LIST FILES) + list(APPEND GLOB_BUT_NOT_LIST ${file}) + endif() + endforeach() + if(GLOB_BUT_NOT_LIST) + message(AUTHOR_WARNING "Entries only present in ${DIRECTORY}: ${GLOB_BUT_NOT_LIST}") + endif() + if(NOT LIST_BUT_NOT_GLOB AND NOT GLOB_BUT_NOT_LIST) + message(AUTHOR_WARNING "${VAR} is not alphabetically sorted") + endif() + endif() + endif() + + set(${VAR} ${FILES} PARENT_SCOPE) +endfunction() + +function(set_src VAR GLOBBING DIRECTORY) # ... + set_glob(${VAR} ${GLOBBING} "c;cpp;h" ${DIRECTORY} ${ARGN}) + set(${VAR} ${${VAR}} PARENT_SCOPE) +endfunction() + +######################################################################## +# INITIALIZE TARGET LISTS +######################################################################## + +set(TARGETS_OWN) +set(TARGETS_DEP) + +set(TARGETS_LINK) # Targets with a linking stage. + +######################################################################## +# DEPENDENCIES +######################################################################## + +function(set_extra_dirs_lib VARIABLE NAME) + set("PATHS_${VARIABLE}_LIBDIR" PARENT_SCOPE) + set("HINTS_${VARIABLE}_LIBDIR" PARENT_SCOPE) + if(PREFER_BUNDLED_LIBS) + set(TYPE HINTS) + else() + set(TYPE PATHS) + endif() + if(TARGET_BITS AND TARGET_OS) + set(DIR "other/${NAME}/${TARGET_OS}/lib${TARGET_BITS}") + set("${TYPE}_${VARIABLE}_LIBDIR" "${DIR}" PARENT_SCOPE) + set("EXTRA_${VARIABLE}_LIBDIR" "${DIR}" PARENT_SCOPE) + endif() +endfunction() + +function(set_extra_dirs_include VARIABLE NAME LIBRARY) + set("PATHS_${VARIABLE}_INCLUDEDIR" PARENT_SCOPE) + set("HINTS_${VARIABLE}_INCLUDEDIR" PARENT_SCOPE) + is_bundled(IS_BUNDLED "${LIBRARY}") + if(IS_BUNDLED) + set("HINTS_${VARIABLE}_INCLUDEDIR" "other/${NAME}/include" "other/${NAME}/include/${TARGET_OS}" PARENT_SCOPE) + endif() +endfunction() + +if(CMAKE_CROSSCOMPILING) + set(CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH NO_CMAKE_SYSTEM_PATH) +else() + set(CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH) +endif() + +function(is_bundled VARIABLE PATH) + if(PATH) + string(FIND "${PATH}" "${PROJECT_SOURCE_DIR}" LOCAL_PATH_POS) + if(LOCAL_PATH_POS EQUAL 0 AND TARGET_BITS AND TARGET_OS) + set("${VARIABLE}" ON PARENT_SCOPE) + else() + set("${VARIABLE}" OFF PARENT_SCOPE) + endif() + else() + set("${VARIABLE}" OFF PARENT_SCOPE) + endif() +endfunction() + +if(NOT CMAKE_CROSSCOMPILING) + # Check for PkgConfig once so all the other `find_package` calls can do it + # quietly. + find_package(PkgConfig) +endif() +find_package(ZLIB) +find_package(Crypto) +find_package(Freetype) +find_package(Git) +find_package(GTest) +find_package(Pnglite) +find_package(SDL2) +find_package(Threads) +find_package(Wavpack) + + +if(TARGET_OS AND TARGET_OS STREQUAL "mac") + find_program(CMAKE_OTOOL otool) + find_program(DMG dmg) + find_program(HFSPLUS hfsplus) + find_program(NEWFS_HFS newfs_hfs) + if(DMG AND HFSPLUS AND NEWFS_HFS) + set(DMGTOOLS_FOUND ON) + else() + set(DMGTOOLS_FOUND OFF) + endif() + + find_program(HDIUTIL hdiutil) + if(HDIUTIL) + set(HDIUTIL_FOUND ON) + else() + set(HDIUTIL_FOUND OFF) + endif() +endif() + +message(STATUS "******** Teeworlds ********") +message(STATUS "Target OS: ${TARGET_OS} ${TARGET_BITS}bit") +message(STATUS "Compiler: ${CMAKE_CXX_COMPILER}") +message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") + +message(STATUS "Dependencies:") +function(show_dependency_status OUTPUT_NAME NAME) + if(${NAME}_FOUND) + if(${NAME}_BUNDLED) + message(STATUS " * ${OUTPUT_NAME} not found (using bundled version)") + else() + message(STATUS " * ${OUTPUT_NAME} found") + endif() + else() + message(STATUS " * ${OUTPUT_NAME} not found") + endif() +endfunction() + +if(TARGET_OS AND TARGET_OS STREQUAL "mac") + show_dependency_status("Dmg tools" DMGTOOLS) +endif() +show_dependency_status("Freetype" FREETYPE) +if(TARGET_OS AND TARGET_OS STREQUAL "mac") + show_dependency_status("Hdiutil" HDIUTIL) +endif() +show_dependency_status("OpenSSL Crypto" CRYPTO) +show_dependency_status("Pnglite" PNGLITE) +show_dependency_status("PythonInterp" PYTHONINTERP) +show_dependency_status("SDL2" SDL2) +show_dependency_status("Wavpack" WAVPACK) +show_dependency_status("Zlib" ZLIB) + +if(NOT(PYTHONINTERP_FOUND)) + message(SEND_ERROR "You must install Python to compile Teeworlds") +endif() + +if(CLIENT AND NOT(FREETYPE_FOUND)) + message(SEND_ERROR "You must install Freetype to compile the Teeworlds client") +endif() +if(CLIENT AND NOT(SDL2_FOUND)) + message(SEND_ERROR "You must install SDL2 to compile the Teeworlds client") +endif() +if(NOT(GTEST_FOUND)) + if(DOWNLOAD_GTEST) + if(GIT_FOUND) + message(STATUS "Automatically downloading GTest to be able to run tests") + else() + set(DOWNLOAD_GTEST OFF) + message(WARNING "To automatically download GTest, you have to install Git") + endif() + else() + message(STATUS "To run the tests, you have to install GTest") + endif() +endif() + +if(TARGET_OS STREQUAL "windows") + set(PLATFORM_CLIENT) + set(PLATFORM_CLIENT_LIBS opengl32 winmm imm32) + set(PLATFORM_LIBS ws2_32) # Windows sockets +elseif(TARGET_OS STREQUAL "mac") + find_library(CARBON Carbon) + find_library(COCOA Cocoa) + find_library(OPENGL OpenGL) + set(PLATFORM_CLIENT + src/osxlaunch/client.m + ) + set(PLATFORM_CLIENT_LIBS ${COCOA} ${OPENGL}) + set(PLATFORM_LIBS ${CARBON}) +else() + set(PLATFORM_CLIENT) + find_package(OpenGL) + if(CMAKE_VERSION VERSION_LESS 3.10) + set(PLATFORM_CLIENT_LIBS ${OPENGL_gl_LIBRARY}) + else() + set(PLATFORM_CLIENT_LIBS ${OPENGL_opengl_LIBRARY}) + endif() + set(PLATFORM_CLIENT_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR}) + if(TARGET_OS STREQUAL "linux") + set(PLATFORM_LIBS rt) # clock_gettime for glibc < 2.17 + else() + set(PLATFORM_LIBS) + endif() +endif() + +######################################################################## +# DOWNLOAD GTEST +######################################################################## + +if(NOT(GTEST_FOUND) AND DOWNLOAD_GTEST) + set(TEEWORLDS_GTEST_VERSION release-1.8.1) + configure_file(cmake/Download_GTest_CMakeLists.txt.in googletest-download/CMakeLists.txt) + execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . + RESULT_VARIABLE result + WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download + ) + if(result) + message(WARNING "CMake step for googletest failed: ${result}") + set(DOWNLOAD_GTEST OFF) + else() + execute_process(COMMAND ${CMAKE_COMMAND} --build . + RESULT_VARIABLE result + WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download + ) + if(result) + message(WARNING "Build step for googletest failed: ${result}") + set(DOWNLOAD_GTEST OFF) + else() + file(GLOB_RECURSE DDNET_GTEST_CMAKELISTS ${CMAKE_BINARY_DIR}/googletest-src/CMakeLists.txt) + foreach(file ${DDNET_GTEST_CMAKELISTS}) + file(READ ${file} CONTENTS) + string(REPLACE "cmake_minimum_required(VERSION 2.6.4)" "cmake_minimum_required(VERSION 2.8.12...3.19.1)" CONTENTS "${CONTENTS}") + string(REPLACE "cmake_minimum_required(VERSION 2.6.4)" "cmake_minimum_required(VERSION 2.8.12...3.19.1)" CONTENTS "${CONTENTS}") + string(REPLACE "cmake_minimum_required(VERSION 2.8.8)" "cmake_minimum_required(VERSION 2.8.12...3.19.1)" CONTENTS "${CONTENTS}") + file(WRITE ${file} "${CONTENTS}") + endforeach() + + # Prevent overriding the parent project's compiler/linker settings on Windows + set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + + # Add googletest directly to our build. This defines the gtest target. + add_subdirectory( + ${PROJECT_BINARY_DIR}/googletest-src + ${PROJECT_BINARY_DIR}/googletest-build + EXCLUDE_FROM_ALL + ) + + if(MSVC) + foreach(target gtest) + # `/w` disables all warnings. This is needed because `gtest` enables + # `/WX` (equivalent of `-Werror`) for some reason, breaking builds + # when MSVS adds new warnings. + target_compile_options(${target} PRIVATE /w) + if(POLICY CMP0091) + set_property(TARGET ${target} PROPERTY MSVC_RUNTIME_LIBRARY MultiThreaded$<${DBG}:Debug>) + else() + target_compile_options(${target} PRIVATE $<$:/MT> $<${DBG}:/MTd>) + endif() + endforeach() + endif() + + set(GTEST_LIBRARIES gtest) + set(GTEST_INCLUDE_DIRS) + if(CMAKE_VERSION VERSION_LESS 2.8.11) + set(GTEST_INCLUDE_DIRS "${gtest_SOURCE_DIR}/include") + endif() + endif() + endif() +endif() + +######################################################################## +# DEPENDENCY COMPILATION +######################################################################## + +set_src(DEP_JSON_SRC GLOB src/engine/external/json-parser json.c json.h) +add_library(json EXCLUDE_FROM_ALL OBJECT ${DEP_JSON_SRC}) + +set_src(DEP_MD5_SRC GLOB src/engine/external/md5 md5.c md5.h) +add_library(md5 EXCLUDE_FROM_ALL OBJECT ${DEP_MD5_SRC}) + +list(APPEND TARGETS_DEP json md5) +set(DEP_JSON $) +set(DEP_MD5) +if(NOT CRYPTO_FOUND) + set(DEP_MD5 $) +endif() + +######################################################################## +# DATA +######################################################################## + +set(EXPECTED_DATA + audio/foley_body_impact-01.wv + audio/foley_body_impact-02.wv + audio/foley_body_impact-03.wv + audio/foley_body_splat-01.wv + audio/foley_body_splat-02.wv + audio/foley_body_splat-03.wv + audio/foley_body_splat-04.wv + audio/foley_dbljump-01.wv + audio/foley_dbljump-02.wv + audio/foley_dbljump-03.wv + audio/foley_foot_left-01.wv + audio/foley_foot_left-02.wv + audio/foley_foot_left-03.wv + audio/foley_foot_left-04.wv + audio/foley_foot_right-01.wv + audio/foley_foot_right-02.wv + audio/foley_foot_right-03.wv + audio/foley_foot_right-04.wv + audio/foley_land-01.wv + audio/foley_land-02.wv + audio/foley_land-03.wv + audio/foley_land-04.wv + audio/hook_attach-01.wv + audio/hook_attach-02.wv + audio/hook_attach-03.wv + audio/hook_loop-01.wv + audio/hook_loop-02.wv + audio/hook_noattach-01.wv + audio/hook_noattach-02.wv + audio/hook_noattach-03.wv + audio/music_menu.wv + audio/sfx_ctf_cap_pl.wv + audio/sfx_ctf_drop.wv + audio/sfx_ctf_grab_en.wv + audio/sfx_ctf_grab_pl.wv + audio/sfx_ctf_rtn.wv + audio/sfx_hit_strong-01.wv + audio/sfx_hit_strong-02.wv + audio/sfx_hit_weak-01.wv + audio/sfx_hit_weak-02.wv + audio/sfx_hit_weak-03.wv + audio/sfx_msg-client.wv + audio/sfx_msg-highlight.wv + audio/sfx_msg-server.wv + audio/sfx_pickup_arm-01.wv + audio/sfx_pickup_arm-02.wv + audio/sfx_pickup_arm-03.wv + audio/sfx_pickup_arm-04.wv + audio/sfx_pickup_gun.wv + audio/sfx_pickup_hrt-01.wv + audio/sfx_pickup_hrt-02.wv + audio/sfx_pickup_launcher.wv + audio/sfx_pickup_ninja.wv + audio/sfx_pickup_sg.wv + audio/sfx_skid-01.wv + audio/sfx_skid-02.wv + audio/sfx_skid-03.wv + audio/sfx_skid-04.wv + audio/sfx_spawn_wpn-01.wv + audio/sfx_spawn_wpn-02.wv + audio/sfx_spawn_wpn-03.wv + audio/vo_teefault_cry-01.wv + audio/vo_teefault_cry-02.wv + audio/vo_teefault_ninja-01.wv + audio/vo_teefault_ninja-02.wv + audio/vo_teefault_ninja-03.wv + audio/vo_teefault_ninja-04.wv + audio/vo_teefault_pain_long-01.wv + audio/vo_teefault_pain_long-02.wv + audio/vo_teefault_pain_short-01.wv + audio/vo_teefault_pain_short-02.wv + audio/vo_teefault_pain_short-03.wv + audio/vo_teefault_pain_short-04.wv + audio/vo_teefault_pain_short-05.wv + audio/vo_teefault_pain_short-06.wv + audio/vo_teefault_pain_short-07.wv + audio/vo_teefault_pain_short-08.wv + audio/vo_teefault_pain_short-09.wv + audio/vo_teefault_pain_short-10.wv + audio/vo_teefault_pain_short-11.wv + audio/vo_teefault_pain_short-12.wv + audio/vo_teefault_sledge-01.wv + audio/vo_teefault_sledge-02.wv + audio/vo_teefault_sledge-03.wv + audio/vo_teefault_spawn-01.wv + audio/vo_teefault_spawn-02.wv + audio/vo_teefault_spawn-03.wv + audio/vo_teefault_spawn-04.wv + audio/vo_teefault_spawn-05.wv + audio/vo_teefault_spawn-06.wv + audio/vo_teefault_spawn-07.wv + audio/wp_flump_explo-01.wv + audio/wp_flump_explo-02.wv + audio/wp_flump_explo-03.wv + audio/wp_flump_launch-01.wv + audio/wp_flump_launch-02.wv + audio/wp_flump_launch-03.wv + audio/wp_gun_fire-01.wv + audio/wp_gun_fire-02.wv + audio/wp_gun_fire-03.wv + audio/wp_hammer_hit-01.wv + audio/wp_hammer_hit-02.wv + audio/wp_hammer_hit-03.wv + audio/wp_hammer_swing-01.wv + audio/wp_hammer_swing-02.wv + audio/wp_hammer_swing-03.wv + audio/wp_laser_bnce-01.wv + audio/wp_laser_bnce-02.wv + audio/wp_laser_bnce-03.wv + audio/wp_laser_fire-01.wv + audio/wp_laser_fire-02.wv + audio/wp_laser_fire-03.wv + audio/wp_ninja_attack-01.wv + audio/wp_ninja_attack-02.wv + audio/wp_ninja_attack-03.wv + audio/wp_ninja_attack-04.wv + audio/wp_ninja_hit-01.wv + audio/wp_ninja_hit-02.wv + audio/wp_ninja_hit-03.wv + audio/wp_ninja_hit-04.wv + audio/wp_noammo-01.wv + audio/wp_noammo-02.wv + audio/wp_noammo-03.wv + audio/wp_noammo-04.wv + audio/wp_noammo-05.wv + audio/wp_shotty_fire-01.wv + audio/wp_shotty_fire-02.wv + audio/wp_shotty_fire-03.wv + audio/wp_switch-01.wv + audio/wp_switch-02.wv + audio/wp_switch-03.wv + countryflags/AD.png + countryflags/AE.png + countryflags/AF.png + countryflags/AG.png + countryflags/AI.png + countryflags/AL.png + countryflags/AM.png + countryflags/AO.png + countryflags/AR.png + countryflags/AS.png + countryflags/AT.png + countryflags/AU.png + countryflags/AW.png + countryflags/AX.png + countryflags/AZ.png + countryflags/BA.png + countryflags/BB.png + countryflags/BD.png + countryflags/BE.png + countryflags/BF.png + countryflags/BG.png + countryflags/BH.png + countryflags/BI.png + countryflags/BJ.png + countryflags/BL.png + countryflags/BM.png + countryflags/BN.png + countryflags/BO.png + countryflags/BR.png + countryflags/BS.png + countryflags/BT.png + countryflags/BW.png + countryflags/BY.png + countryflags/BZ.png + countryflags/CA.png + countryflags/CC.png + countryflags/CD.png + countryflags/CF.png + countryflags/CG.png + countryflags/CH.png + countryflags/CI.png + countryflags/CK.png + countryflags/CL.png + countryflags/CM.png + countryflags/CN.png + countryflags/CO.png + countryflags/CR.png + countryflags/CU.png + countryflags/CV.png + countryflags/CW.png + countryflags/CX.png + countryflags/CY.png + countryflags/CZ.png + countryflags/DE.png + countryflags/DJ.png + countryflags/DK.png + countryflags/DM.png + countryflags/DO.png + countryflags/DZ.png + countryflags/EC.png + countryflags/EE.png + countryflags/EG.png + countryflags/EH.png + countryflags/ER.png + countryflags/ES.png + countryflags/ET.png + countryflags/FI.png + countryflags/FJ.png + countryflags/FK.png + countryflags/FM.png + countryflags/FO.png + countryflags/FR.png + countryflags/GA.png + countryflags/GB.png + countryflags/GD.png + countryflags/GE.png + countryflags/GF.png + countryflags/GG.png + countryflags/GH.png + countryflags/GI.png + countryflags/GL.png + countryflags/GM.png + countryflags/GN.png + countryflags/GP.png + countryflags/GQ.png + countryflags/GR.png + countryflags/GS.png + countryflags/GT.png + countryflags/GU.png + countryflags/GW.png + countryflags/GY.png + countryflags/HK.png + countryflags/HN.png + countryflags/HR.png + countryflags/HT.png + countryflags/HU.png + countryflags/ID.png + countryflags/IE.png + countryflags/IL.png + countryflags/IM.png + countryflags/IN.png + countryflags/IO.png + countryflags/IQ.png + countryflags/IR.png + countryflags/IS.png + countryflags/IT.png + countryflags/JE.png + countryflags/JM.png + countryflags/JO.png + countryflags/JP.png + countryflags/KE.png + countryflags/KG.png + countryflags/KH.png + countryflags/KI.png + countryflags/KM.png + countryflags/KN.png + countryflags/KP.png + countryflags/KR.png + countryflags/KW.png + countryflags/KY.png + countryflags/KZ.png + countryflags/LA.png + countryflags/LB.png + countryflags/LC.png + countryflags/LI.png + countryflags/LK.png + countryflags/LR.png + countryflags/LS.png + countryflags/LT.png + countryflags/LU.png + countryflags/LV.png + countryflags/LY.png + countryflags/MA.png + countryflags/MC.png + countryflags/MD.png + countryflags/ME.png + countryflags/MF.png + countryflags/MG.png + countryflags/MH.png + countryflags/MK.png + countryflags/ML.png + countryflags/MM.png + countryflags/MN.png + countryflags/MO.png + countryflags/MP.png + countryflags/MQ.png + countryflags/MR.png + countryflags/MS.png + countryflags/MT.png + countryflags/MU.png + countryflags/MV.png + countryflags/MW.png + countryflags/MX.png + countryflags/MY.png + countryflags/MZ.png + countryflags/NA.png + countryflags/NC.png + countryflags/NE.png + countryflags/NF.png + countryflags/NG.png + countryflags/NI.png + countryflags/NL.png + countryflags/NO.png + countryflags/NP.png + countryflags/NR.png + countryflags/NU.png + countryflags/NZ.png + countryflags/OM.png + countryflags/PA.png + countryflags/PE.png + countryflags/PF.png + countryflags/PG.png + countryflags/PH.png + countryflags/PK.png + countryflags/PL.png + countryflags/PM.png + countryflags/PN.png + countryflags/PR.png + countryflags/PS.png + countryflags/PT.png + countryflags/PW.png + countryflags/PY.png + countryflags/QA.png + countryflags/RE.png + countryflags/RO.png + countryflags/RS.png + countryflags/RU.png + countryflags/RW.png + countryflags/SA.png + countryflags/SB.png + countryflags/SC.png + countryflags/SD.png + countryflags/SE.png + countryflags/SG.png + countryflags/SH.png + countryflags/SI.png + countryflags/SK.png + countryflags/SL.png + countryflags/SM.png + countryflags/SN.png + countryflags/SO.png + countryflags/SR.png + countryflags/SS.png + countryflags/ST.png + countryflags/SV.png + countryflags/SX.png + countryflags/SY.png + countryflags/SZ.png + countryflags/TC.png + countryflags/TD.png + countryflags/TF.png + countryflags/TG.png + countryflags/TH.png + countryflags/TJ.png + countryflags/TK.png + countryflags/TL.png + countryflags/TM.png + countryflags/TN.png + countryflags/TO.png + countryflags/TR.png + countryflags/TT.png + countryflags/TV.png + countryflags/TW.png + countryflags/TZ.png + countryflags/UA.png + countryflags/UG.png + countryflags/US.png + countryflags/UY.png + countryflags/UZ.png + countryflags/VA.png + countryflags/VC.png + countryflags/VE.png + countryflags/VG.png + countryflags/VI.png + countryflags/VN.png + countryflags/VU.png + countryflags/WF.png + countryflags/WS.png + countryflags/XBZ.png + countryflags/XCA.png + countryflags/XEN.png + countryflags/XES.png + countryflags/XGA.png + countryflags/XNI.png + countryflags/XSC.png + countryflags/XWA.png + countryflags/YE.png + countryflags/ZA.png + countryflags/ZM.png + countryflags/ZW.png + countryflags/default.png + countryflags/index.json + deadtee.png + editor/automap/desert_main.json + editor/automap/grass_doodads.json + editor/automap/grass_main.json + editor/automap/jungle_deathtiles.json + editor/automap/jungle_main.json + editor/automap/winter_main.json + editor/background.png + editor/checker.png + editor/cursor.png + editor/entities.png + emoticons.png + fonts/DejaVuSans.ttf + fonts/SourceHanSans.ttc + fonts/index.json + game.png + languages/belarusian.json + languages/bosnian.json + languages/brazilian_portuguese.json + languages/breton.json + languages/bulgarian.json + languages/catalan.json + languages/chuvash.json + languages/czech.json + languages/danish.json + languages/dutch.json + languages/esperanto.json + languages/estonian.json + languages/finnish.json + languages/french.json + languages/gaelic_scottish.json + languages/galician.json + languages/german.json + languages/greek.json + languages/hungarian.json + languages/index.json + languages/irish.json + languages/italian.json + languages/japanese.json + languages/korean.json + languages/kyrgyz.json + languages/license.txt + languages/lithuanian.json + languages/norwegian.json + languages/polish.json + languages/portuguese.json + languages/readme.txt + languages/romanian.json + languages/russian.json + languages/serbian.json + languages/simplified_chinese.json + languages/slovak.json + languages/slovenian.json + languages/spanish.json + languages/swedish.json + languages/traditional_chinese.json + languages/turkish.json + languages/ukrainian.json + mapres/bg_cloud1.png + mapres/bg_cloud2.png + mapres/bg_cloud3.png + mapres/desert_doodads.png + mapres/desert_main.png + mapres/desert_mountains.png + mapres/desert_mountains2.png + mapres/desert_sun.png + mapres/easter.png + mapres/generic_deathtiles.png + mapres/generic_lamps.png + mapres/generic_shadows.png + mapres/generic_unhookable.png + mapres/grass_doodads.png + mapres/grass_main.png + mapres/jungle_background.png + mapres/jungle_deathtiles.png + mapres/jungle_doodads.png + mapres/jungle_main.png + mapres/jungle_midground.png + mapres/jungle_unhookables.png + mapres/light.png + mapres/moon.png + mapres/mountains.png + mapres/snow.png + mapres/stars.png + mapres/sun.png + mapres/winter_doodads.png + mapres/winter_main.png + mapres/winter_mountains.png + mapres/winter_mountains2.png + mapres/winter_mountains3.png + maps/ctf1.map + maps/ctf2.map + maps/ctf3.map + maps/ctf4.map + maps/ctf5.map + maps/ctf6.map + maps/ctf7.map + maps/ctf8.map + maps/dm1.map + maps/dm2.map + maps/dm3.map + maps/dm6.map + maps/dm7.map + maps/dm8.map + maps/dm9.map + maps/license.txt + maps/lms1.map + maps/readme.txt + particles.png + race_flag.png + skins/beaver.json + skins/bluekitty.json + skins/bluestripe.json + skins/body/bat.png + skins/body/bear.png + skins/body/beaver.png + skins/body/dog.png + skins/body/force.png + skins/body/fox.png + skins/body/hippo.png + skins/body/kitty.png + skins/body/koala.png + skins/body/monkey.png + skins/body/mouse.png + skins/body/piglet.png + skins/body/raccoon.png + skins/body/spiky.png + skins/body/standard.png + skins/body/x_ninja.png + skins/bot.png + skins/brownbear.json + skins/bumbler.json + skins/cammo.json + skins/cammostripes.json + skins/cavebat.json + skins/decoration/hair.png + skins/decoration/twinbopp.png + skins/decoration/twinmello.png + skins/decoration/twinpen.png + skins/decoration/unibop.png + skins/decoration/unimelo.png + skins/decoration/unipento.png + skins/default.json + skins/eyes/colorable.png + skins/eyes/negative.png + skins/eyes/standard.png + skins/eyes/standardreal.png + skins/eyes/x_ninja.png + skins/feet/standard.png + skins/force.json + skins/fox.json + skins/greycoon.json + skins/greyfox.json + skins/hands/standard.png + skins/hippo.json + skins/koala.json + skins/limedog.json + skins/limekitty.json + skins/marking/bear.png + skins/marking/belly1.png + skins/marking/belly2.png + skins/marking/blush.png + skins/marking/bug.png + skins/marking/cammo1.png + skins/marking/cammo2.png + skins/marking/cammostripes.png + skins/marking/coonfluff.png + skins/marking/donny.png + skins/marking/downdony.png + skins/marking/duodonny.png + skins/marking/fox.png + skins/marking/hipbel.png + skins/marking/lowcross.png + skins/marking/lowpaint.png + skins/marking/marksman.png + skins/marking/mice.png + skins/marking/mixture1.png + skins/marking/mixture2.png + skins/marking/monkey.png + skins/marking/panda1.png + skins/marking/panda2.png + skins/marking/purelove.png + skins/marking/saddo.png + skins/marking/setisu.png + skins/marking/sidemarks.png + skins/marking/singu.png + skins/marking/stripe.png + skins/marking/striped.png + skins/marking/stripes.png + skins/marking/stripes2.png + skins/marking/thunder.png + skins/marking/tiger1.png + skins/marking/tiger2.png + skins/marking/toptri.png + skins/marking/triangular.png + skins/marking/tricircular.png + skins/marking/tripledon.png + skins/marking/tritri.png + skins/marking/twinbelly.png + skins/marking/twincross.png + skins/marking/twintri.png + skins/marking/uppy.png + skins/marking/warpaint.png + skins/marking/warstripes.png + skins/marking/whisker.png + skins/marking/wildpaint.png + skins/marking/wildpatch.png + skins/marking/yinyang.png + skins/monkey.json + skins/paintgre.json + skins/pandabear.json + skins/panther.json + skins/pento.json + skins/piggy.json + skins/pinky.json + skins/raccoon.json + skins/redbopp.json + skins/redstripe.json + skins/saddo.json + skins/setisu.json + skins/snowti.json + skins/spiky.json + skins/swardy.json + skins/tiger.json + skins/tooxy.json + skins/toptri.json + skins/twinbop.json + skins/twintri.json + skins/warmouse.json + skins/warpaint.json + skins/x_ninja.json + skins/xmas_hat.png + ui/blob.png + ui/console.png + ui/console_bar.png + ui/debug_font.png + ui/demo_buttons.png + ui/file_icons.png + ui/gametypes/ctf.png + ui/gametypes/dm.png + ui/gametypes/lms.png + ui/gametypes/lts.png + ui/gametypes/mod.png + ui/gametypes/race.png + ui/gametypes/tdm.png + ui/gui_buttons.png + ui/gui_cursor.png + ui/gui_icons.png + ui/gui_logo.png + ui/icons/arrows.png + ui/icons/browse.png + ui/icons/browser.png + ui/icons/chat_whisper.png + ui/icons/friend.png + ui/icons/level.png + ui/icons/menu.png + ui/icons/network.png + ui/icons/sidebar.png + ui/icons/timer_clock.png + ui/icons/tools.png + ui/menuimages/demos.png + ui/menuimages/editor.png + ui/menuimages/local_server.png + ui/menuimages/play_game.png + ui/menuimages/settings.png + ui/no_skinpart.png + ui/sound_icons.png + ui/themes/auto.png + ui/themes/heavens.png + ui/themes/heavens_day.map + ui/themes/heavens_night.map + ui/themes/jungle.png + ui/themes/jungle_day.map + ui/themes/jungle_night.map + ui/themes/none.png + ui/themes/winter.png + ui/themes/winter_day.map + ui/themes/winter_night.map +) + +if(NOT EXISTS ${PROJECT_SOURCE_DIR}/datasrc/languages/index.json) + message(WARNING "Missing datasrc/languages submodule. Please download a source release or update your git submodules with `git submodule update --init`") + foreach(item ${EXPECTED_DATA}) + if(item MATCHES "^languages/") + list(REMOVE_ITEM EXPECTED_DATA ${item}) + endif() + endforeach() +endif() + +if(NOT EXISTS ${PROJECT_SOURCE_DIR}/datasrc/maps/dm1.map) + message(WARNING "Missing datasrc/maps submodule. Please download a source release or update your git submodules with `git submodule update --init`") + foreach(item ${EXPECTED_DATA}) + if(item MATCHES "^maps/") + list(REMOVE_ITEM EXPECTED_DATA ${item}) + endif() + endforeach() +endif() + +set_glob(DATA GLOB_RECURSE "json;map;png;rules;ttc;ttf;txt;wv" datasrc ${EXPECTED_DATA}) + +######################################################################## +# COPY DATA AND DLLS +######################################################################## + +foreach(datafile ${DATA}) + file(RELATIVE_PATH OUT ${PROJECT_SOURCE_DIR}/datasrc ${datafile}) + get_filename_component(DESTINATION data/${OUT} PATH) + file(MAKE_DIRECTORY ${DESTINATION}) + file(COPY ${datafile} DESTINATION ${DESTINATION}) +endforeach() +set(COPY_FILES + ${FREETYPE_COPY_FILES} + ${SDL2_COPY_FILES} +) +file(COPY ${COPY_FILES} DESTINATION .) + +######################################################################## +# CODE GENERATION +######################################################################## + +function(chash output_file) + add_custom_command(OUTPUT ${output_file} + COMMAND ${PYTHON_EXECUTABLE} scripts/cmd5.py ${ARGN} + > "${PROJECT_BINARY_DIR}/${output_file}" + DEPENDS scripts/cmd5.py ${ARGN} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) +endfunction() + +function(generate_source output_file script_parameter) + add_custom_command(OUTPUT ${output_file} + COMMAND ${PYTHON_EXECUTABLE} datasrc/compile.py ${script_parameter} + > "${PROJECT_BINARY_DIR}/${output_file}" + DEPENDS + datasrc/compile.py + datasrc/content.py + datasrc/datatypes.py + datasrc/network.py + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) +endfunction() + +file(MAKE_DIRECTORY "${PROJECT_BINARY_DIR}/src/generated/") +if(GIT_FOUND) + execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir + ERROR_QUIET + OUTPUT_VARIABLE PROJECT_GIT_DIR + OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE PROJECT_GIT_DIR_ERROR + ) + if(NOT PROJECT_GIT_DIR_ERROR) + set(GIT_REVISION_EXTRA_DEPS + ${PROJECT_GIT_DIR}/index + ${PROJECT_GIT_DIR}/logs/HEAD + ) + endif() +endif() +add_custom_command(OUTPUT ${PROJECT_BINARY_DIR}/src/generated/git_revision.cpp + COMMAND ${PYTHON_EXECUTABLE} + scripts/git_revision.py + > ${PROJECT_BINARY_DIR}/src/generated/git_revision.cpp + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + DEPENDS + ${GIT_REVISION_EXTRA_DEPS} + scripts/git_revision.py +) +chash("src/generated/nethash.cpp" + "src/engine/shared/protocol.h" + "src/game/tuning.h" + "src/game/gamecore.cpp" + "${PROJECT_BINARY_DIR}/src/generated/protocol.h" +) +generate_source("src/generated/client_data.cpp" "client_content_source") +generate_source("src/generated/client_data.h" "client_content_header") +generate_source("src/generated/protocol.cpp" "network_source") +generate_source("src/generated/protocol.h" "network_header") +generate_source("src/generated/server_data.cpp" "server_content_source") +generate_source("src/generated/server_data.h" "server_content_header") + + +######################################################################## +# SHARED +######################################################################## + +# Sources +set_src(BASE GLOB_RECURSE src/base + color.h + detect.h + hash.c + hash.h + hash_bundled.c + hash_ctxt.h + hash_libtomcrypt.c + hash_openssl.c + math.h + system.c + system.h + tl/algorithm.h + tl/allocator.h + tl/array.h + tl/range.h + tl/sorted_array.h + tl/string.h + tl/threading.h + vmath.h +) +set_src(ENGINE_INTERFACE GLOB src/engine + client.h + config.h + console.h + contacts.h + demo.h + editor.h + engine.h + graphics.h + input.h + kernel.h + keys.h + map.h + mapchecker.h + masterserver.h + message.h + server.h + serverbrowser.h + sound.h + storage.h + textrender.h +) +set_src(ENGINE_SHARED GLOB src/engine/shared + compression.cpp + compression.h + config.cpp + config.h + config_variables.h + console.cpp + console.h + datafile.cpp + datafile.h + demo.cpp + demo.h + econ.cpp + econ.h + engine.cpp + filecollection.cpp + filecollection.h + huffman.cpp + huffman.h + jobs.cpp + jobs.h + jsonwriter.cpp + jsonwriter.h + kernel.cpp + linereader.cpp + linereader.h + map.cpp + mapchecker.cpp + mapchecker.h + masterserver.cpp + memheap.cpp + memheap.h + netban.cpp + netban.h + network.cpp + network.h + network_client.cpp + network_conn.cpp + network_console.cpp + network_console_conn.cpp + network_server.cpp + network_token.cpp + packer.cpp + packer.h + protocol.h + ringbuffer.cpp + ringbuffer.h + snapshot.cpp + snapshot.h + storage.cpp +) +set(ENGINE_GENERATED_SHARED src/generated/nethash.cpp src/generated/protocol.cpp src/generated/protocol.h) +set_src(GAME_SHARED GLOB src/game + collision.cpp + collision.h + commands.h + gamecore.cpp + gamecore.h + layers.cpp + layers.h + mapitems.h + tuning.h + variables.h + version.h + voting.h +) +set(GAME_GENERATED_SHARED + src/generated/git_revision.cpp + src/generated/nethash.cpp + src/generated/protocol.h +) + +set(DEPS ${DEP_JSON} ${DEP_MD5} ${ZLIB_DEP}) + +# Libraries +set(LIBS ${CMAKE_THREAD_LIBS_INIT} ${ZLIB_LIBRARIES} ${CRYPTO_LIBRARIES} ${PLATFORM_LIBS}) + +# Targets +add_library(engine-shared EXCLUDE_FROM_ALL OBJECT ${ENGINE_INTERFACE} ${ENGINE_SHARED} ${ENGINE_GENERATED_SHARED} ${BASE}) +add_library(game-shared EXCLUDE_FROM_ALL OBJECT ${GAME_SHARED} ${GAME_GENERATED_SHARED}) +list(APPEND TARGETS_OWN engine-shared game-shared) + + +######################################################################## +# CLIENT +######################################################################## + +if(CLIENT) + # Sources + set_src(ENGINE_CLIENT GLOB src/engine/client + backend_sdl.cpp + backend_sdl.h + client.cpp + client.h + contacts.cpp + contacts.h + graphics_threaded.cpp + graphics_threaded.h + graphics_threaded_null.h + input.cpp + input.h + keynames.h + serverbrowser.cpp + serverbrowser.h + serverbrowser_entry.h + serverbrowser_fav.cpp + serverbrowser_fav.h + serverbrowser_filter.cpp + serverbrowser_filter.h + sound.cpp + sound.h + textrender.cpp + textrender.h + ) + set_src(GAME_CLIENT GLOB_RECURSE src/game/client + animstate.cpp + animstate.h + component.h + components/binds.cpp + components/binds.h + components/broadcast.cpp + components/broadcast.h + components/camera.cpp + components/camera.h + components/chat.cpp + components/chat.h + components/console.cpp + components/console.h + components/controls.cpp + components/controls.h + components/countryflags.cpp + components/countryflags.h + components/damageind.cpp + components/damageind.h + components/debughud.cpp + components/debughud.h + components/effects.cpp + components/effects.h + components/emoticon.cpp + components/emoticon.h + components/flow.cpp + components/flow.h + components/hud.cpp + components/hud.h + components/infomessages.cpp + components/infomessages.h + components/items.cpp + components/items.h + components/mapimages.cpp + components/mapimages.h + components/maplayers.cpp + components/maplayers.h + components/menus.cpp + components/menus.h + components/menus_browser.cpp + components/menus_callback.cpp + components/menus_demo.cpp + components/menus_ingame.cpp + components/menus_settings.cpp + components/menus_start.cpp + components/motd.cpp + components/motd.h + components/nameplates.cpp + components/nameplates.h + components/notifications.cpp + components/notifications.h + components/particles.cpp + components/particles.h + components/players.cpp + components/players.h + components/scoreboard.cpp + components/scoreboard.h + components/skins.cpp + components/skins.h + components/sounds.cpp + components/sounds.h + components/spectator.cpp + components/spectator.h + components/stats.cpp + components/stats.h + components/voting.cpp + components/voting.h + gameclient.cpp + gameclient.h + lineinput.cpp + lineinput.h + localization.cpp + localization.h + render.cpp + render.h + render_map.cpp + ui.cpp + ui.h + ui_listbox.cpp + ui_listbox.h + ui_rect.cpp + ui_rect.h + ui_scrollregion.cpp + ui_scrollregion.h + ) + set_src(GAME_EDITOR GLOB src/game/editor + auto_map.cpp + auto_map.h + editor.cpp + editor.h + io.cpp + layer_game.cpp + layer_quads.cpp + layer_tiles.cpp + popups.cpp + ) + set(GAME_GENERATED_CLIENT + src/generated/client_data.cpp + src/generated/client_data.h + ) + set(CLIENT_SRC ${PLATFORM_CLIENT} ${ENGINE_CLIENT} ${GAME_CLIENT} ${GAME_EDITOR} ${GAME_GENERATED_CLIENT}) + + set(DEPS_CLIENT ${DEPS} ${PNGLITE_DEP} ${WAVPACK_DEP}) + + # Libraries + set(LIBS_CLIENT + ${LIBS} + ${FREETYPE_LIBRARIES} + ${PNGLITE_LIBRARIES} + ${SDL2_LIBRARIES} + ${WAVPACK_LIBRARIES} + ${PLATFORM_CLIENT_LIBS} + ) + + if(TARGET_OS STREQUAL "windows") + set(CLIENT_ICON "other/icons/${CLIENT_EXECUTABLE}.rc") + if(NOT MINGW) + set(CLIENT_MANIFEST "other/manifest/teeworlds.manifest") + else() + set(CLIENT_MANIFEST "other/manifest/teeworlds.rc") + endif() + else() + set(CLIENT_ICON) + endif() + + # Target + set(TARGET_CLIENT ${CLIENT_EXECUTABLE}) + add_executable(${TARGET_CLIENT} + ${CLIENT_SRC} + ${CLIENT_ICON} + ${CLIENT_MANIFEST} + ${DEPS_CLIENT} + $ + $ + ) + target_link_libraries(${TARGET_CLIENT} ${LIBS_CLIENT}) + + target_include_directories(${TARGET_CLIENT} PRIVATE + ${FREETYPE_INCLUDE_DIRS} + ${PNGLITE_INCLUDE_DIRS} + ${SDL2_INCLUDE_DIRS} + ${WAVPACK_INCLUDE_DIRS} + ) + + set(PARAMS "${WAVPACK_INCLUDE_DIRS};${WAVPACK_INCLUDE_DIRS}") + if(NOT(WAVPACK_OPEN_FILE_INPUT_EX_PARAMS STREQUAL PARAMS)) + unset(WAVPACK_OPEN_FILE_INPUT_EX CACHE) + endif() + set(WAVPACK_OPEN_FILE_INPUT_EX_PARAMS "${PARAMS}" CACHE INTERNAL "") + + set(CMAKE_REQUIRED_INCLUDES ${ORIGINAL_CMAKE_REQUIRED_INCLUDES} ${WAVPACK_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${ORIGINAL_CMAKE_REQUIRED_LIBRARIES} ${WAVPACK_LIBRARIES}) + check_symbol_exists(WavpackOpenFileInputEx wavpack.h WAVPACK_OPEN_FILE_INPUT_EX) + set(CMAKE_REQUIRED_INCLUDES ${ORIGINAL_CMAKE_REQUIRED_INCLUDES}) + set(CMAKE_REQUIRED_LIBRARIES ${ORIGINAL_CMAKE_REQUIRED_LIBRARIES}) + + if(WAVPACK_OPEN_FILE_INPUT_EX) + target_compile_definitions(${TARGET_CLIENT} PRIVATE CONF_WAVPACK_OPEN_FILE_INPUT_EX) + endif() + + list(APPEND TARGETS_OWN ${TARGET_CLIENT}) + list(APPEND TARGETS_LINK ${TARGET_CLIENT}) +endif() + + +######################################################################## +# SERVER +######################################################################## + +# Sources +set_src(ENGINE_SERVER GLOB src/engine/server + register.cpp + register.h + server.cpp + server.h +) +set_src(GAME_SERVER GLOB_RECURSE src/game/server + alloc.h + entities/character.cpp + entities/character.h + entities/flag.cpp + entities/flag.h + entities/laser.cpp + entities/laser.h + entities/pickup.cpp + entities/pickup.h + entities/projectile.cpp + entities/projectile.h + entity.cpp + entity.h + eventhandler.cpp + eventhandler.h + gamecontext.cpp + gamecontext.h + gamecontroller.cpp + gamecontroller.h + gamemodes/ctf.cpp + gamemodes/ctf.h + gamemodes/dm.cpp + gamemodes/dm.h + gamemodes/lms.cpp + gamemodes/lms.h + gamemodes/lts.cpp + gamemodes/lts.h + gamemodes/mod.cpp + gamemodes/mod.h + gamemodes/tdm.cpp + gamemodes/tdm.h + gameworld.cpp + gameworld.h + player.cpp + player.h +) +set(GAME_GENERATED_SERVER + src/generated/server_data.cpp + src/generated/server_data.h +) +set(SERVER_SRC ${ENGINE_SERVER} ${GAME_SERVER} ${GAME_GENERATED_SERVER}) +if(TARGET_OS STREQUAL "windows") + set(SERVER_ICON "other/icons/${SERVER_EXECUTABLE}.rc") +else() + set(SERVER_ICON) +endif() + +# Libraries +set(LIBS_SERVER ${LIBS}) + +# Target +set(TARGET_SERVER ${SERVER_EXECUTABLE}) +add_executable(${TARGET_SERVER} + ${DEPS} + ${SERVER_SRC} + ${SERVER_ICON} + $ + $ +) +target_link_libraries(${TARGET_SERVER} ${LIBS_SERVER}) +list(APPEND TARGETS_OWN ${TARGET_SERVER}) +list(APPEND TARGETS_LINK ${TARGET_SERVER}) + +if(TARGET_OS AND TARGET_OS STREQUAL "mac") + set(SERVER_LAUNCHER_SRC src/osxlaunch/server.mm) + set(TARGET_SERVER_LAUNCHER ${TARGET_SERVER}-Launcher) + add_executable(${TARGET_SERVER_LAUNCHER} ${SERVER_LAUNCHER_SRC}) + target_link_libraries(${TARGET_SERVER_LAUNCHER} ${COCOA}) + list(APPEND TARGETS_OWN ${TARGET_SERVER_LAUNCHER}) + list(APPEND TARGETS_LINK ${TARGET_SERVER_LAUNCHER}) +endif() + +######################################################################## +# VARIOUS TARGETS +######################################################################## + +set_src(MASTERSRV_SRC GLOB src/mastersrv mastersrv.cpp mastersrv.h) +set_src(VERSIONSRV_SRC GLOB src/versionsrv mapversions.h versionsrv.cpp versionsrv.h) +list(APPEND VERSIONSRV_SRC ${PROJECT_BINARY_DIR}/src/generated/nethash.cpp) + +set(TARGET_MASTERSRV mastersrv) +set(TARGET_VERSIONSRV versionsrv) + +add_executable(${TARGET_MASTERSRV} EXCLUDE_FROM_ALL ${MASTERSRV_SRC} $ ${DEPS}) +add_executable(${TARGET_VERSIONSRV} EXCLUDE_FROM_ALL ${VERSIONSRV_SRC} $ ${DEPS}) + +target_link_libraries(${TARGET_MASTERSRV} ${LIBS}) +target_link_libraries(${TARGET_VERSIONSRV} ${LIBS}) + +list(APPEND TARGETS_OWN ${TARGET_MASTERSRV} ${TARGET_VERSIONSRV}) +list(APPEND TARGETS_LINK ${TARGET_MASTERSRV} ${TARGET_VERSIONSRV}) + +set(TARGETS_TOOLS) +set_src(TOOLS GLOB src/tools + crapnet.cpp + fake_server.cpp + map_resave.cpp + map_version.cpp + packetgen.cpp +) +foreach(ABS_T ${TOOLS}) + file(RELATIVE_PATH T "${PROJECT_SOURCE_DIR}/src/tools/" ${ABS_T}) + if(T MATCHES "\\.cpp$") + string(REGEX REPLACE "\\.cpp$" "" TOOL "${T}") + add_executable(${TOOL} EXCLUDE_FROM_ALL + ${DEPS} + src/tools/${TOOL}.cpp + ${EXTRA_TOOL_SRC} + $ + ) + target_link_libraries(${TOOL} ${LIBS}) + list(APPEND TARGETS_TOOLS ${TOOL}) + endif() +endforeach() + +list(APPEND TARGETS_OWN ${TARGETS_TOOLS}) +list(APPEND TARGETS_LINK ${TARGETS_TOOLS}) + +add_custom_target(tools DEPENDS ${TARGETS_TOOLS}) +add_custom_target(everything DEPENDS ${TARGETS_OWN}) + +######################################################################## +# TESTS +######################################################################## + +if(GTEST_FOUND OR DOWNLOAD_GTEST) + set_src(TESTS GLOB src/test + bytes_be.cpp + compression.cpp + datafile.cpp + fs.cpp + git_revision.cpp + hash.cpp + io.cpp + jsonwriter.cpp + sorted_array.cpp + storage.cpp + str.cpp + test.cpp + test.h + thread.cpp + ) + set(TARGET_TESTRUNNER testrunner) + add_executable(${TARGET_TESTRUNNER} EXCLUDE_FROM_ALL + ${TESTS} + $ + $ + ${DEPS} + ) + target_link_libraries(${TARGET_TESTRUNNER} ${LIBS} ${GTEST_LIBRARIES}) + target_include_directories(${TARGET_TESTRUNNER} PRIVATE ${GTEST_INCLUDE_DIRS}) + + list(APPEND TARGETS_OWN ${TARGET_TESTRUNNER}) + list(APPEND TARGETS_LINK ${TARGET_TESTRUNNER}) + + add_custom_target(run_tests + COMMAND $ ${TESTRUNNER_ARGS} + COMMENT Running tests + DEPENDS ${TARGET_TESTRUNER} + USES_TERMINAL + ) +endif() + +######################################################################## +# INSTALLATION +######################################################################## + +function(escape_regex VAR STRING) + string(REGEX REPLACE "([][^$.+*?|()\\\\])" "\\\\\\1" ESCAPED "${STRING}") + set(${VAR} ${ESCAPED} PARENT_SCOPE) +endfunction() + +function(escape_backslashes VAR STRING) + string(REGEX REPLACE "\\\\" "\\\\\\\\" ESCAPED "${STRING}") + set(${VAR} ${ESCAPED} PARENT_SCOPE) +endfunction() + +function(max_length VAR) + set(MAX_LENGTH 0) + foreach(str ${ARGN}) + string(LENGTH ${str} LENGTH) + if(LENGTH GREATER MAX_LENGTH) + set(MAX_LENGTH ${LENGTH}) + endif() + endforeach() + set(${VAR} ${MAX_LENGTH} PARENT_SCOPE) +endfunction() + +# Tries to generate a list of regex that matches everything except the given +# parameters. +function(regex_inverted VAR) + max_length(MAX_LENGTH ${ARGN}) + math(EXPR UPPER_BOUND "${MAX_LENGTH}-1") + + set(REMAINING ${ARGN}) + set(RESULT) + + foreach(i RANGE ${UPPER_BOUND}) + set(TEMP ${REMAINING}) + set(REMAINING) + foreach(str ${TEMP}) + string(LENGTH ${str} LENGTH) + if(i LESS LENGTH) + list(APPEND REMAINING ${str}) + endif() + endforeach() + + set(ADDITIONAL) + foreach(outer ${REMAINING}) + string(SUBSTRING ${outer} 0 ${i} OUTER_PREFIX) + set(CHARS "") + foreach(inner ${REMAINING}) + string(SUBSTRING ${inner} 0 ${i} INNER_PREFIX) + if(OUTER_PREFIX STREQUAL INNER_PREFIX) + string(SUBSTRING ${inner} ${i} 1 INNER_NEXT) + set(CHARS "${CHARS}${INNER_NEXT}") + endif() + endforeach() + escape_regex(OUTER_PREFIX_ESCAPED "${OUTER_PREFIX}") + + list(APPEND ADDITIONAL "${OUTER_PREFIX_ESCAPED}([^${CHARS}]|$)") + endforeach() + list(REMOVE_DUPLICATES ADDITIONAL) + list(APPEND RESULT ${ADDITIONAL}) + endforeach() + set(${VAR} ${RESULT} PARENT_SCOPE) +endfunction() + +set(CPACK_PACKAGE_NAME ${PROJECT_NAME}) +set(CPACK_GENERATOR TGZ TXZ) +set(CPACK_ARCHIVE_COMPONENT_INSTALL ON) +set(CPACK_STRIP_FILES TRUE) +set(CPACK_COMPONENTS_ALL portable) +set(CPACK_SOURCE_GENERATOR ZIP TGZ TBZ2 TXZ) +set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) +set(CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}) +set(CPACK_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}) + +if(TARGET_OS AND TARGET_BITS) + if(TARGET_OS STREQUAL "windows") + set(CPACK_SYSTEM_NAME "win${TARGET_BITS}") + set(CPACK_GENERATOR ZIP) + elseif(TARGET_OS STREQUAL "linux") + # Assuming Intel here. + if(TARGET_BITS EQUAL 32) + set(CPACK_SYSTEM_NAME "linux_x86") + elseif(TARGET_BITS EQUAL 64) + set(CPACK_SYSTEM_NAME "linux_x86_64") + endif() + elseif(TARGET_OS STREQUAL "mac") + set(CPACK_SYSTEM_NAME "osx") + set(CPACK_GENERATOR DMG) + endif() +endif() + +set(CPACK_PACKAGE_FILE_NAME ${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_SYSTEM_NAME}) +set(CPACK_ARCHIVE_PORTABLE_FILE_NAME ${CPACK_PACKAGE_FILE_NAME}) +set(CPACK_SOURCE_PACKAGE_FILE_NAME ${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-src) +set(CPACK_SOURCE_FILES + CMakeLists.txt + bam.lua + cmake/ + configure.lua + datasrc/ + license.txt + other/ + readme.md + scripts/ + src/ + storage.cfg +) +set(CPACK_SOURCE_IGNORE_FILES + "\\\\.o$" + "\\\\.pyc$" + "/\\\\.git" + "/__pycache__/" +) + +regex_inverted(CPACK_SOURCE_FILES_INVERTED ${CPACK_SOURCE_FILES}) +escape_regex(PROJECT_SOURCE_DIR_ESCAPED ${PROJECT_SOURCE_DIR}) + +foreach(str ${CPACK_SOURCE_FILES_INVERTED}) + escape_backslashes(STR_ESCAPED "${PROJECT_SOURCE_DIR_ESCAPED}/${str}") + list(APPEND CPACK_SOURCE_IGNORE_FILES "${STR_ESCAPED}") +endforeach() + +set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME ${PROJECT_NAME}) + +set(CPACK_TARGETS + ${TARGET_CLIENT} + ${TARGET_SERVER} +) +set(CPACK_DIRS ${PROJECT_BINARY_DIR}/data) +set(CPACK_FILES + license.txt + storage.cfg + ${COPY_FILES} +) +if(TARGET_OS STREQUAL "windows") + list(APPEND CPACK_FILES other/config_directory.bat) +endif() + +if(NOT DEV) + install(DIRECTORY ${PROJECT_BINARY_DIR}/data DESTINATION share/${PROJECT_NAME} COMPONENT data) + install(TARGETS ${TARGET_CLIENT} DESTINATION bin COMPONENT client) + install(TARGETS ${TARGET_SERVER} DESTINATION bin COMPONENT server) +endif() + +if(DEV) + # Don't generate CPack targets. +elseif(CMAKE_VERSION VERSION_LESS 3.6 OR CMAKE_VERSION VERSION_EQUAL 3.6) + message(WARNING "Cannot create CPack targets, CMake version too old. Use CMake 3.6 or newer.") +else() + set(EXTRA_ARGS DESTINATION ${CPACK_PACKAGE_FILE_NAME} COMPONENT portable EXCLUDE_FROM_ALL) + install(TARGETS ${CPACK_TARGETS} ${EXTRA_ARGS}) + install(DIRECTORY ${CPACK_DIRS} ${EXTRA_ARGS}) + install(FILES ${CPACK_FILES} ${EXTRA_ARGS}) +endif() + +set(PACKAGE_TARGETS) + +if(CLIENT AND (DMGTOOLS_FOUND OR HDIUTIL)) + file(MAKE_DIRECTORY bundle/client/) + file(MAKE_DIRECTORY bundle/server/) + configure_file(other/bundle/client/Info.plist.in bundle/client/Info.plist) + configure_file(other/bundle/server/Info.plist.in bundle/server/Info.plist) + + if(HDIUTIL) + set(DMG_PARAMS --hdiutil ${HDIUTIL}) + elseif(DMGTOOLS_FOUND) + set(DMG_PARAMS --dmgtools ${DMG} ${HFSPLUS} ${NEWFS_HFS}) + endif() + set(DMG_TMPDIR pack_${CPACK_PACKAGE_FILE_NAME}_dmg) + set(DMG_MKDIRS + ${TARGET_CLIENT}.app + ${TARGET_CLIENT}.app/Contents + ${TARGET_CLIENT}.app/Contents/Frameworks + ${TARGET_CLIENT}.app/Contents/MacOS + ${TARGET_CLIENT}.app/Contents/Resources + ${TARGET_SERVER}.app + ${TARGET_SERVER}.app/Contents + ${TARGET_SERVER}.app/Contents/MacOS + ${TARGET_SERVER}.app/Contents/Resources + ${TARGET_SERVER}.app/Contents/Resources/data + # Needed so the server recognizes the data directory. + ${TARGET_SERVER}.app/Contents/Resources/data/mapres + ) + set(DMG_MKDIR_COMMANDS) + foreach(dir ${DMG_MKDIRS}) + list(APPEND DMG_MKDIR_COMMANDS COMMAND ${CMAKE_COMMAND} -E make_directory ${DMG_TMPDIR}/${dir}) + endforeach() + add_custom_command(OUTPUT ${CPACK_PACKAGE_FILE_NAME}.dmg + COMMAND ${CMAKE_COMMAND} -E remove_directory ${DMG_TMPDIR} + ${DMG_MKDIR_COMMANDS} + + # CLIENT + COMMAND ${CMAKE_COMMAND} -E copy_directory data ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/Resources/data + COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/other/icons/${TARGET_CLIENT}.icns ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/Resources/ + COMMAND ${CMAKE_COMMAND} -E copy bundle/client/Info.plist ${PROJECT_SOURCE_DIR}/other/bundle/client/PkgInfo ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/ + COMMAND ${CMAKE_COMMAND} -E copy $ ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/MacOS/ + COMMAND ${CMAKE_COMMAND} -E copy ${SDL2_LIBRARY} ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/Frameworks/libSDL2-2.0.0.dylib + COMMAND ${CMAKE_COMMAND} -E copy ${FREETYPE_LIBRARY} ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/Frameworks/libfreetype.6.dylib + COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/scripts/darwin_change_dylib.py change --tools ${CMAKE_INSTALL_NAME_TOOL} ${CMAKE_OTOOL} ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/MacOS/${TARGET_CLIENT} SDL2 @executable_path/../Frameworks/libSDL2-2.0.0.dylib + COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/scripts/darwin_change_dylib.py change --tools ${CMAKE_INSTALL_NAME_TOOL} ${CMAKE_OTOOL} ${DMG_TMPDIR}/${TARGET_CLIENT}.app/Contents/MacOS/${TARGET_CLIENT} libfreetype @executable_path/../Frameworks/libfreetype.6.dylib + + # SERVER + COMMAND ${CMAKE_COMMAND} -E copy_directory data/maps ${DMG_TMPDIR}/${TARGET_SERVER}.app/Contents/Resources/data/maps + COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/other/icons/${TARGET_SERVER}.icns ${DMG_TMPDIR}/${TARGET_SERVER}.app/Contents/Resources/ + COMMAND ${CMAKE_COMMAND} -E copy bundle/server/Info.plist ${PROJECT_SOURCE_DIR}/other/bundle/server/PkgInfo ${DMG_TMPDIR}/${TARGET_SERVER}.app/Contents/ + COMMAND ${CMAKE_COMMAND} -E copy $ $ ${DMG_TMPDIR}/${TARGET_SERVER}.app/Contents/MacOS/ + + # DMG + COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/scripts/dmg.py create ${DMG_PARAMS} ${CPACK_PACKAGE_FILE_NAME}.dmg ${CPACK_PACKAGE_FILE_NAME} ${DMG_TMPDIR} + + DEPENDS + ${TARGET_CLIENT} + ${TARGET_SERVER_LAUNCHER} + ${TARGET_SERVER} + ${PROJECT_BINARY_DIR}/bundle/client/Info.plist + ${PROJECT_BINARY_DIR}/bundle/server/Info.plist + other/bundle/client/PkgInfo + other/bundle/server/PkgInfo + other/icons/${TARGET_CLIENT}.icns + other/icons/${TARGET_SERVER}.icns + scripts/dmg.py + ) + add_custom_target(package_dmg DEPENDS ${CPACK_PACKAGE_FILE_NAME}.dmg) + list(APPEND PACKAGE_TARGETS package_dmg) +endif() + +foreach(ext zip tar.gz tar.xz) + set(TAR_MODE c) + set(TAR_EXTRA_ARGS) + string(REPLACE . _ EXT_SLUG ${ext}) + + set(TMPDIR pack_${CPACK_PACKAGE_FILE_NAME}_${EXT_SLUG}/${CPACK_PACKAGE_FILE_NAME}) + + set(COPY_FILE_COMMANDS) + set(COPY_DIR_COMMANDS) + set(COPY_TARGET_COMMANDS) + set(STRIP_TARGET_COMMANDS) + foreach(file ${CPACK_FILES}) + list(APPEND COPY_FILE_COMMANDS COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/${file} ${TMPDIR}/) + endforeach() + foreach(dir ${CPACK_DIRS}) + get_filename_component(NAME ${dir} NAME) + list(APPEND COPY_DIR_COMMANDS COMMAND ${CMAKE_COMMAND} -E copy_directory ${dir} ${TMPDIR}/${NAME}) + endforeach() + foreach(target ${CPACK_TARGETS}) + list(APPEND COPY_TARGET_COMMANDS COMMAND ${CMAKE_COMMAND} -E copy $ ${TMPDIR}/) + endforeach() + + if(ext STREQUAL zip) + set(TAR_EXTRA_ARGS --format=zip) + elseif(ext STREQUAL tar.gz) + set(TAR_MODE cz) + elseif(ext STREQUAL tar.xz) + set(TAR_MODE cJ) + endif() + add_custom_command(OUTPUT ${CPACK_PACKAGE_FILE_NAME}.${ext} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${TMPDIR} + COMMAND ${CMAKE_COMMAND} -E make_directory ${TMPDIR} + ${COPY_FILE_COMMANDS} + ${COPY_DIR_COMMANDS} + ${COPY_TARGET_COMMANDS} + ${STRIP_TARGET_COMMANDS} + COMMAND ${CMAKE_COMMAND} -E chdir pack_${CPACK_PACKAGE_FILE_NAME}_${EXT_SLUG} ${CMAKE_COMMAND} -E tar ${TAR_MODE} ../${CPACK_PACKAGE_FILE_NAME}.${ext} ${TAR_EXTRA_ARGS} -- ${CPACK_PACKAGE_FILE_NAME}/ + DEPENDS ${CPACK_TARGETS} + ) + add_custom_target(package_${EXT_SLUG} DEPENDS ${CPACK_PACKAGE_FILE_NAME}.${ext}) + list(APPEND PACKAGE_TARGETS package_${EXT_SLUG}) +endforeach() + +set(PACKAGE_DEFAULT tar_xz) +if(TARGET_OS STREQUAL "windows") + set(PACKAGE_DEFAULT zip) +elseif(TARGET_OS STREQUAL "mac") + set(PACKAGE_DEFAULT dmg) +endif() +add_custom_target(package_default DEPENDS package_${PACKAGE_DEFAULT}) + +add_custom_target(package_all DEPENDS ${PACKAGE_TARGETS}) + +# Unset these variables, they might do something in the future of CPack. +unset(CPACK_SOURCE_FILES) +unset(CPACK_SOURCE_FILES_INVERTED) +unset(CPACK_TARGETS) +unset(CPACK_DIRS) +unset(CPACK_FILES) + +include(CPack) + +######################################################################## +# COMPILER-SPECIFICS +######################################################################## + +# In the future (CMake 3.8.0+), use source_group(TREE ...) +macro(source_group_tree dir) + file(GLOB ents RELATIVE ${PROJECT_SOURCE_DIR}/${dir} ${PROJECT_SOURCE_DIR}/${dir}/*) + foreach(ent ${ents}) + if(IS_DIRECTORY ${PROJECT_SOURCE_DIR}/${dir}/${ent}) + source_group_tree(${dir}/${ent}) + else() + string(REPLACE "/" "\\" group ${dir}) + source_group(${group} FILES ${PROJECT_SOURCE_DIR}/${dir}/${ent}) + endif() + endforeach() +endmacro() +source_group_tree(src) + +set(TARGETS ${TARGETS_OWN} ${TARGETS_DEP}) + +foreach(target ${TARGETS}) + if(MSVC) + if(POLICY CMP0091) + set_property(TARGET ${target} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<${DBG}:Debug>") + else() + target_compile_options(${target} PRIVATE $<$:/MT> $<${DBG}:/MTd>) + endif() + target_compile_options(${target} PRIVATE /MP) # Use multiple cores + target_compile_options(${target} PRIVATE /EHsc) # Only catch C++ exceptions with catch. + target_compile_options(${target} PRIVATE /GS) # Protect the stack pointer. + target_compile_options(${target} PRIVATE /wd4996) # Use of non-_s functions. + target_compile_options(${target} PRIVATE /utf-8) # Use UTF-8 for source files. + endif() + if(OUR_FLAGS) + target_compile_options(${target} PRIVATE ${OUR_FLAGS}) + endif() + if(DEFINE_FORTIFY_SOURCE) + target_compile_definitions(${target} PRIVATE $<$>:_FORTIFY_SOURCE=2>) # Detect some buffer overflows. + endif() + target_compile_definitions(${target} PRIVATE _GLIBCXX_ASSERTIONS) # Enable run-time bounds-checking for the STL +endforeach() + +foreach(target ${TARGETS_LINK}) + if(MSVC) + set_property(TARGET ${target} APPEND PROPERTY LINK_FLAGS /SAFESEH:NO) # Disable SafeSEH because the shipped libraries don't support it (would cause error LNK2026 otherwise). + endif() + if(TARGET_OS STREQUAL "mac") + target_link_libraries(${target} -stdlib=libc++) + target_link_libraries(${target} -mmacosx-version-min=10.7) + endif() + if((MINGW OR TARGET_OS STREQUAL "linux") AND PREFER_BUNDLED_LIBS) + # Statically link the standard libraries with on MinGW/Linux so we don't + # have to ship them as DLLs. + target_link_libraries(${target} -static-libgcc) + target_link_libraries(${target} -static-libstdc++) + if(MINGW) + # Link pthread library statically instead of dynamically. + # Solution from https://stackoverflow.com/a/28001261. + target_link_libraries(${target} -Wl,-Bstatic -lstdc++ -lpthread -Wl,-Bdynamic) + endif() + endif() +endforeach() + +foreach(target ${TARGETS_OWN}) + if(MSVC) + target_compile_options(${target} PRIVATE /W3) + target_compile_options(${target} PRIVATE /wd4244) # Possible loss of data (float -> int, int -> float, etc.). + target_compile_options(${target} PRIVATE /wd4267) # Possible loss of data (size_t - int on win64). + target_compile_options(${target} PRIVATE /wd4800) # Implicit conversion of int to bool. + endif() + if(TARGET_OS STREQUAL "windows") + target_compile_definitions(${target} PRIVATE UNICODE) # Windows headers + target_compile_definitions(${target} PRIVATE _UNICODE) # C-runtime + endif() + if(OUR_FLAGS_OWN) + target_compile_options(${target} PRIVATE ${OUR_FLAGS_OWN}) + endif() + target_include_directories(${target} PRIVATE ${PROJECT_BINARY_DIR}/src) + target_include_directories(${target} PRIVATE src) + target_compile_definitions(${target} PRIVATE $<$:CONF_DEBUG>) + target_include_directories(${target} PRIVATE ${CURL_INCLUDE_DIRS}) + target_include_directories(${target} PRIVATE ${ZLIB_INCLUDE_DIRS}) + if(CRYPTO_FOUND) + target_compile_definitions(${target} PRIVATE CONF_OPENSSL) + target_include_directories(${target} PRIVATE ${CRYPTO_INCLUDE_DIRS}) + endif() + if(HEADLESS_CLIENT) + target_compile_definitions(${target} PRIVATE CONF_HEADLESS_CLIENT) + endif() +endforeach() + +foreach(target ${TARGETS_DEP}) + if(MSVC) + target_compile_options(${target} PRIVATE /W0) + endif() + if(OUR_FLAGS_DEP) + target_compile_options(${target} PRIVATE ${OUR_FLAGS_DEP}) + endif() +endforeach() diff --git a/bam.lua b/bam.lua new file mode 100644 index 000000000..fe3be07af --- /dev/null +++ b/bam.lua @@ -0,0 +1,507 @@ +CheckVersion("0.5") + +Import("configure.lua") + +--- Setup Config ------- +config = NewConfig() +config:Add(OptCCompiler("compiler")) +config:Add(OptTestCompileC("stackprotector", "int main(){return 0;}", "-fstack-protector -fstack-protector-all")) +config:Add(OptTestCompileC("minmacosxsdk", "int main(){return 0;}", "-mmacosx-version-min=10.7 -isysroot /Developer/SDKs/MacOSX10.7.sdk")) +config:Add(OptTestCompileC("buildwithoutsseflag", "#include \nint main(){_mm_pause();return 0;}", "")) +config:Add(OptLibrary("zlib", "zlib.h", false)) +config:Finalize("config.lua") + +generated_src_dir = "build/src" +generated_icon_dir = "build/icons" +builddir = "build/" +content_src_dir = "datasrc/" + +python_in_path = ExecuteSilent("python -V") == 0 + +-- data compiler +function Python(name) + if family == "windows" then + name = str_replace(name, "/", "\\") + if not python_in_path then + -- Python is usually registered for .py files in Windows + return name + end + end + return "python " .. name +end + +function CHash(output, ...) + local inputs = TableFlatten({...}) + + output = PathJoin(generated_src_dir, Path(output)) + + -- compile all the files + local cmd = Python("scripts/cmd5.py") .. " " + for index, inname in ipairs(inputs) do + cmd = cmd .. Path(inname) .. " " + end + + cmd = cmd .. " > " .. output + + AddJob(output, "cmd5 " .. output, cmd) + for index, inname in ipairs(inputs) do + AddDependency(output, inname) + end + AddDependency(output, "scripts/cmd5.py") + return output +end + +function ResCompile(scriptfile, compiler) + scriptfile = Path(scriptfile) + local output = nil + if compiler == "cl" then + output = PathJoin(generated_icon_dir, PathBase(PathFilename(scriptfile)) .. ".res") + AddJob(output, "rc " .. scriptfile, "rc /fo " .. output .. " " .. scriptfile) + elseif compiler == "gcc" or compiler == "clang" then + output = PathJoin(generated_icon_dir, PathBase(PathFilename(scriptfile)) .. ".coff") + AddJob(output, "windres " .. scriptfile, "windres -i " .. scriptfile .. " -o " .. output) + end + AddDependency(output, scriptfile) + return output +end + +function ContentCompile(action, output) + output = PathJoin(generated_src_dir, Path(output)) + AddJob( + output, + action .. " > " .. output, + Python("datasrc/compile.py") .. " " .. action .. " > " .. output + ) + AddDependency(output, "datasrc/compile.py") + AddDependency("datasrc/compile.py", "datasrc/content.py", "datasrc/network.py", "datasrc/datatypes.py") + return output +end + + +function GenerateCommonSettings(settings, conf, arch, compiler) + if compiler == "gcc" or compiler == "clang" then + settings.cc.flags:Add("-Wall", "-fno-exceptions") + end + + -- Compile zlib if needed + local zlib = nil + if config.zlib.value == 1 then + settings.link.libs:Add("z") + if config.zlib.include_path then + settings.cc.includes:Add(config.zlib.include_path) + end + else + settings.cc.includes:Add("src/engine/external/zlib") + zlib = Compile(settings, Collect("src/engine/external/zlib/*.c")) + end + + local md5 = Compile(settings, Collect("src/engine/external/md5/*.c")) + local json = Compile(settings, Collect("src/engine/external/json-parser/*.c")) + + -- globally available libs + libs = {zlib=zlib, md5=md5, json=json} +end + +function GenerateMacOSXSettings(settings, conf, arch, compiler) + if arch == "x86" then + settings.cc.flags:Add("-arch i386") + settings.link.flags:Add("-arch i386") + elseif arch == "x86_64" then + settings.cc.flags:Add("-arch x86_64") + settings.link.flags:Add("-arch x86_64") + elseif arch == "ppc" then + settings.cc.flags:Add("-arch ppc") + settings.link.flags:Add("-arch ppc") + elseif arch == "ppc64" then + settings.cc.flags:Add("-arch ppc64") + settings.link.flags:Add("-arch ppc64") + else + print("Unknown Architecture '" .. arch .. "'. Supported: x86, x86_64, ppc, ppc64") + os.exit(1) + end + + -- c++ stdlib needed + settings.cc.flags:Add("--stdlib=libc++") + settings.link.flags:Add("--stdlib=libc++") + -- this also needs the macOS min SDK version to be at least 10.7 + + settings.cc.flags:Add("-mmacosx-version-min=10.7") + settings.link.flags:Add("-mmacosx-version-min=10.7") + + if config.minmacosxsdk.value == 1 then + settings.cc.flags:Add("-isysroot /Developer/SDKs/MacOSX10.7.sdk") + settings.link.flags:Add("-isysroot /Developer/SDKs/MacOSX10.7.sdk") + end + + settings.link.frameworks:Add("Carbon") + settings.link.frameworks:Add("AppKit") + + GenerateCommonSettings(settings, conf, arch, compiler) + + -- Build server launcher before adding game stuff + local serverlaunch = Link(settings, "serverlaunch", Compile(settings, "src/osxlaunch/server.m")) + + -- Master server, version server and tools + BuildEngineCommon(settings) + BuildMasterserver(settings) + BuildVersionserver(settings) + BuildTools(settings) + + -- Add requirements for Server + BuildGameCommon(settings) + + -- Server + settings.link.frameworks:Add("Cocoa") + local server_exe = BuildServer(settings) + AddDependency(server_exe, serverlaunch) + + -- Content + BuildContent(settings, arch, conf) +end + +function GenerateLinuxSettings(settings, conf, arch, compiler) + if arch == "x86" then + if config.buildwithoutsseflag.value == false then + settings.cc.flags:Add("-msse2") -- for the _mm_pause call + end + settings.cc.flags:Add("-m32") + settings.link.flags:Add("-m32") + elseif arch == "x86_64" then + settings.cc.flags:Add("-m64") + settings.link.flags:Add("-m64") + elseif arch == "armv7l" then + -- arm 32 bit + else + print("Unknown Architecture '" .. arch .. "'. Supported: x86, x86_64") + os.exit(1) + end + settings.link.libs:Add("pthread") + + GenerateCommonSettings(settings, conf, arch, compiler) + + -- Master server, version server and tools + BuildEngineCommon(settings) + BuildTools(settings) + BuildMasterserver(settings) + BuildVersionserver(settings) + + -- Add requirements for Server + BuildGameCommon(settings) + + -- Server + BuildServer(settings) + + -- Content + BuildContent(settings, arch, conf) +end + +function GenerateSolarisSettings(settings, conf, arch, compiler) + settings.link.libs:Add("socket") + settings.link.libs:Add("nsl") + + GenerateLinuxSettings(settings, conf, arch, compiler) +end + +function GenerateWindowsSettings(settings, conf, target_arch, compiler) + if compiler == "cl" then + if (target_arch == "x86" and arch ~= "ia32") or + (target_arch == "x86_64" and arch ~= "ia64" and arch ~= "amd64") then + print("Cross compiling is unsupported on Windows.") + os.exit(1) + end + settings.cc.flags:Add("/wd4244", "/wd4577") + elseif compiler == "gcc" or config.compiler.driver == "clang" then + if target_arch ~= "x86" and target_arch ~= "x86_64" then + print("Unknown Architecture '" .. arch .. "'. Supported: x86, x86_64") + os.exit(1) + end + + -- disable visibility attribute support for gcc on windows + settings.cc.defines:Add("NO_VIZ") + settings.cc.defines:Add("_WIN32_WINNT=0x0501") + end + + -- Unicode support + settings.cc.defines:Add("UNICODE") -- Windows headers + settings.cc.defines:Add("_UNICODE") -- C-runtime + + local icons = SharedIcons(compiler) + local manifests = SharedManifests(compiler) + + -- Required libs + settings.link.libs:Add("gdi32") + settings.link.libs:Add("user32") + settings.link.libs:Add("ws2_32") + settings.link.libs:Add("ole32") + settings.link.libs:Add("shell32") + settings.link.libs:Add("advapi32") + + GenerateCommonSettings(settings, conf, target_arch, compiler) + + -- Master server, version server and tools + BuildEngineCommon(settings) + BuildMasterserver(settings) + BuildVersionserver(settings) + BuildTools(settings) + + -- Add requirements for Server + BuildGameCommon(settings) + + -- Server + local server_settings = settings:Copy() + server_settings.link.extrafiles:Add(icons.server) + BuildServer(server_settings) + + -- Content + BuildContent(settings, target_arch, conf) +end + +function SharedCommonFiles() + -- Shared game files, generate only once + + if not shared_common_files then + local network_source = ContentCompile("network_source", "generated/protocol.cpp") + local network_header = ContentCompile("network_header", "generated/protocol.h") + AddDependency(network_source, network_header, "src/engine/shared/protocol.h") + + local nethash = CHash("generated/nethash.cpp", "src/engine/shared/protocol.h", "src/game/tuning.h", "src/game/gamecore.cpp", network_header) + shared_common_files = {network_source, nethash} + end + + return shared_common_files +end + +function SharedServerFiles() + -- Shared server files, generate only once + + if not shared_server_files then + local server_content_source = ContentCompile("server_content_source", "generated/server_data.cpp") + local server_content_header = ContentCompile("server_content_header", "generated/server_data.h") + AddDependency(server_content_source, server_content_header) + shared_server_files = {server_content_source} + end + + return shared_server_files +end + +shared_icons = {} +function SharedIcons(compiler) + if not shared_icons[compiler] then + local server_icon = ResCompile("other/icons/teeworlds_srv_" .. compiler .. ".rc", compiler) + local client_icon = ResCompile("other/icons/teeworlds_" .. compiler .. ".rc", compiler) + shared_icons[compiler] = {server=server_icon, client=client_icon} + end + return shared_icons[compiler] +end + +function SharedManifests(compiler) + if not shared_manifests then + local client_manifest = ResCompile("other/manifest/teeworlds.rc", compiler) + shared_manifests = {client=client_manifest} + end + return shared_manifests +end + +function BuildEngineCommon(settings) + settings.link.extrafiles:Merge(Compile(settings, Collect("src/engine/shared/*.cpp", "src/base/*.c"))) +end + +function BuildGameCommon(settings) + settings.link.extrafiles:Merge(Compile(settings, Collect("src/game/*.cpp"), SharedCommonFiles())) +end + +function BuildServer(settings, family, platform) + local server = Compile(settings, Collect("src/engine/server/*.cpp")) + + local game_server = Compile(settings, CollectRecursive("src/game/server/*.cpp"), SharedServerFiles()) + + return Link(settings, "teeworlds_srv", libs["zlib"], libs["md5"], server, game_server) +end + +function BuildTools(settings) + local tools = {} + for i,v in ipairs(Collect("src/tools/*.cpp", "src/tools/*.c")) do + local toolname = PathFilename(PathBase(v)) + tools[i] = Link(settings, toolname, Compile(settings, v), libs["zlib"], libs["md5"], libs["wavpack"], libs["png"]) + end + PseudoTarget(settings.link.Output(settings, "pseudo_tools") .. settings.link.extension, tools) +end + +function BuildMasterserver(settings) + return Link(settings, "mastersrv", Compile(settings, Collect("src/mastersrv/*.cpp")), libs["zlib"], libs["md5"]) +end + +function BuildVersionserver(settings) + return Link(settings, "versionsrv", Compile(settings, Collect("src/versionsrv/*.cpp")), libs["zlib"], libs["md5"]) +end + +function BuildContent(settings, arch, conf) + local content = {} + table.insert(content, CopyToDir(settings.link.Output(builddir, "data"), CollectRecursive(content_src_dir .. "*.png", content_src_dir .. "*.wv", content_src_dir .. "*.ttc", content_src_dir .. "*.ttf", content_src_dir .. "*.txt", content_src_dir .. "*.map", content_src_dir .. "*.rules", content_src_dir .. "*.json"))) + if family == "windows" then + if arch == "x86_64" then + _arch = "64" + else + _arch = "32" + end + -- dependencies + dl = Python("scripts/download.py") + AddJob({ + "other/freetype/include/ft2build.h", "other/freetype/windows/lib" .. _arch .. "/freetype.dll", + "other/sdl/include/SDL.h", "other/sdl/windows/lib" .. _arch .. "/SDL2.dll" + }, "Downloading freetype and SDL2", dl .. " freetype sdl" + ) + table.insert(content, CopyFile(settings.link.Output(settings, "") .. "/SDL2.dll", "other/sdl/windows/lib" .. _arch .. "/SDL2.dll")) + table.insert(content, CopyFile(settings.link.Output(settings, "") .. "/freetype.dll", "other/freetype/windows/lib" .. _arch .. "/freetype.dll")) + AddDependency(settings.link.Output(settings, "") .. "/SDL2.dll", "other/sdl/include/SDL.h") + AddDependency(settings.link.Output(settings, "") .. "/freetype.dll", "other/freetype/include/ft2build.h") + end + PseudoTarget(settings.link.Output(settings, "content") .. settings.link.extension, content) +end + +-- create all targets for specified configuration & architecture +function GenerateSettings(conf, arch, builddir, compiler, headless) + local settings = NewSettings() + + -- Set compiler if explicitly requested + if compiler == "gcc" then + SetDriversGCC(settings) + elseif compiler == "clang" then + SetDriversClang(settings) + elseif compiler == "cl" then + SetDriversCL(settings) + else + -- apply compiler settings + config.compiler:Apply(settings) + compiler = config.compiler.driver + end + + if conf == "debug" then + settings.debug = 1 + settings.optimize = 0 + settings.cc.defines:Add("CONF_DEBUG") + else + settings.debug = 0 + settings.optimize = 1 + settings.cc.defines:Add("CONF_RELEASE") + end + + if headless == "on" then + settings.cc.defines:Add("CONF_HEADLESS_CLIENT") + end + + -- Generate object files in {builddir}/objs/ + settings.cc.Output = function (settings_, input) + -- strip + input = input:gsub("^src/", "") + input = input:gsub("^" .. generated_src_dir .. "/", "") + return PathJoin(PathJoin(builddir, "objs"), PathBase(input)) + end + + -- Build output files in {builddir} + settings.link.Output = function (settings_, input) + return PathJoin(builddir, PathBase(input)) + end + + settings.cc.includes:Add("src") + settings.cc.includes:Add("src/engine/external/pnglite") + settings.cc.includes:Add("src/engine/external/wavpack") + settings.cc.includes:Add(generated_src_dir) + + if family == "windows" then + GenerateWindowsSettings(settings, conf, arch, compiler) + elseif family == "unix" then + if platform == "macosx" then + GenerateMacOSXSettings(settings, conf, arch, compiler) + elseif platform == "solaris" then + GenerateSolarisSettings(settings, conf, arch, compiler) + else -- Linux, BSD + GenerateLinuxSettings(settings, conf, arch, compiler) + end + end + + return settings +end + +-- String formatting with named parameters, by RiciLake http://lua-users.org/wiki/StringInterpolation +function interp(s, tab) + return (s:gsub('%%%((%a%w*)%)([-0-9%.]*[cdeEfgGiouxXsq])', + function(k, fmt) + return tab[k] and ("%"..fmt):format(tab[k]) or '%('..k..')'..fmt + end)) +end + +function CopyToDir(dst, ...) + local output = {} + for filename in TableWalk({...}) do + table.insert(output, CopyFile(PathJoin(dst, string.sub(filename, string.len(content_src_dir)+1)), filename)) + end + return output +end + +function split(str, sep) + local vals = {} + str:gsub("([^,]+)", function(val) table.insert(vals, val) end) + return vals +end + +-- Supported archtitectures: x86, amd64, ppc, ppc64 +if ScriptArgs['arch'] then + archs = split(ScriptArgs['arch']) +else + if arch == "ia32" then + archs = {"x86"} + elseif arch == "ia64" or arch == "amd64" then + archs = {"x86_64"} + else + archs = {arch} + end +end + +if ScriptArgs['conf'] then + confs = split(ScriptArgs['conf']) +else + confs = {"debug"} +end + +if ScriptArgs['compiler'] then + compiler = ScriptArgs['compiler'] +else + compiler = nil +end + +if ScriptArgs['builddir'] then + builddir = ScriptArgs['builddir'] +end + +if ScriptArgs['headless'] then + headless = ScriptArgs['headless'] +else + headless = nil +end + +targets = {client="teeworlds", server="teeworlds_srv", + versionserver="versionsrv", masterserver="mastersrv", + tools="pseudo_tools", content="content"} + +subtargets = {} +for t, cur_target in pairs(targets) do + subtargets[cur_target] = {} +end +for a, cur_arch in ipairs(archs) do + for c, cur_conf in ipairs(confs) do + cur_builddir = interp(builddir, {platform=family, arch=cur_arch, target=cur_target, conf=cur_conf, compiler=compiler}) + local settings = GenerateSettings(cur_conf, cur_arch, cur_builddir, compiler, headless) + for t, cur_target in pairs(targets) do + table.insert(subtargets[cur_target], PathJoin(cur_builddir, cur_target .. settings.link.extension)) + end + end +end + +for cur_name, cur_target in pairs(targets) do + -- Supertarget for all configurations and architectures of that target + PseudoTarget(cur_name, subtargets[cur_target]) +end + +PseudoTarget("game", "server", "content") +DefaultTarget("game") diff --git a/cmake/Download_GTest_CMakeLists.txt.in b/cmake/Download_GTest_CMakeLists.txt.in new file mode 100644 index 000000000..bf8fbfb89 --- /dev/null +++ b/cmake/Download_GTest_CMakeLists.txt.in @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 2.8.12...3.19.1) + +project(googletest-download NONE) + +include(ExternalProject) +ExternalProject_Add(googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG "${TEEWORLDS_GTEST_VERSION}" + SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" + BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" + TLS_VERIFY ON +) diff --git a/cmake/FindCrypto.cmake b/cmake/FindCrypto.cmake new file mode 100644 index 000000000..f765e7157 --- /dev/null +++ b/cmake/FindCrypto.cmake @@ -0,0 +1,19 @@ +if(NOT PREFER_BUNDLED_LIBS) + find_package(OpenSSL) + if(OPENSSL_FOUND) + set(CRYPTO_FOUND ON) + set(CRYPTO_BUNDLED OFF) + set(CRYPTO_LIBRARY ${OPENSSL_CRYPTO_LIBRARY}) + set(CRYPTO_INCLUDEDIR ${OPENSSL_INCLUDE_DIR}) + endif() +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Crypto DEFAULT_MSG CRYPTO_LIBRARY CRYPTO_INCLUDEDIR) + +mark_as_advanced(CRYPTO_LIBRARY CRYPTO_INCLUDEDIR) + +if(CRYPTO_FOUND) + set(CRYPTO_LIBRARIES ${CRYPTO_LIBRARY}) + set(CRYPTO_INCLUDE_DIRS ${CRYPTO_INCLUDEDIR}) +endif() diff --git a/cmake/FindFreetype.cmake b/cmake/FindFreetype.cmake new file mode 100644 index 000000000..347b68442 --- /dev/null +++ b/cmake/FindFreetype.cmake @@ -0,0 +1,37 @@ +if(NOT CMAKE_CROSSCOMPILING) + find_package(PkgConfig QUIET) + pkg_check_modules(PC_FREETYPE freetype2) +endif() + +set_extra_dirs_lib(FREETYPE freetype) +find_library(FREETYPE_LIBRARY + NAMES freetype freetype.6 + HINTS ${HINTS_FREETYPE_LIBDIR} ${PC_FREETYPE_LIBDIR} ${PC_FREETYPE_LIBRARY_DIRS} + PATHS ${PATHS_FREETYPE_LIBDIR} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} +) +set_extra_dirs_include(FREETYPE freetype "${FREETYPE_LIBRARY}") +find_path(FREETYPE_INCLUDEDIR + NAMES config/ftheader.h freetype/config/ftheader.h + PATH_SUFFIXES freetype2 + HINTS ${HINTS_FREETYPE_INCLUDEDIR} ${PC_FREETYPE_INCLUDEDIR} ${PC_FREETYPE_INCLUDE_DIRS} + PATHS ${PATHS_FREETYPE_INCLUDEDIR} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Freetype DEFAULT_MSG FREETYPE_LIBRARY FREETYPE_INCLUDEDIR) + +mark_as_advanced(FREETYPE_LIBRARY FREETYPE_INCLUDEDIR) + +if(FREETYPE_FOUND) + set(FREETYPE_LIBRARIES ${FREETYPE_LIBRARY}) + set(FREETYPE_INCLUDE_DIRS ${FREETYPE_INCLUDEDIR}) + + is_bundled(FREETYPE_BUNDLED "${FREETYPE_LIBRARY}") + if(FREETYPE_BUNDLED AND TARGET_OS STREQUAL "windows") + set(FREETYPE_COPY_FILES "${EXTRA_FREETYPE_LIBDIR}/freetype.dll") + else() + set(FREETYPE_COPY_FILES) + endif() +endif() diff --git a/cmake/FindPnglite.cmake b/cmake/FindPnglite.cmake new file mode 100644 index 000000000..6a877c257 --- /dev/null +++ b/cmake/FindPnglite.cmake @@ -0,0 +1,46 @@ +if(NOT PREFER_BUNDLED_LIBS) + if(NOT CMAKE_CROSSCOMPILING) + find_package(PkgConfig QUIET) + pkg_check_modules(PC_PNGLITE pnglite) + endif() + + find_library(PNGLITE_LIBRARY + NAMES pnglite + HINTS ${PC_PNGLITE_LIBDIR} ${PC_PNGLITE_LIBRARY_DIRS} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} + ) + find_path(PNGLITE_INCLUDEDIR + NAMES pnglite.h + HINTS ${PC_PNGLITE_INCLUDEDIR} ${PC_PNGLITE_INCLUDE_DIRS} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} + ) + + mark_as_advanced(PNGLITE_LIBRARY PNGLITE_INCLUDEDIR) + + if(PNGLITE_LIBRARY AND PNGLITE_INCLUDEDIR) + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Pnglite DEFAULT_MSG PNGLITE_LIBRARY PNGLITE_INCLUDEDIR) + + set(PNGLITE_LIBRARIES ${PNGLITE_LIBRARY}) + set(PNGLITE_INCLUDE_DIRS ${PNGLITE_INCLUDEDIR}) + set(PNGLITE_BUNDLED OFF) + endif() +endif() + +if(NOT PNGLITE_FOUND) + set(PNGLITE_SRC_DIR src/engine/external/pnglite) + set_src(PNGLITE_SRC GLOB ${PNGLITE_SRC_DIR} pnglite.c pnglite.h) + add_library(pnglite EXCLUDE_FROM_ALL OBJECT ${PNGLITE_SRC}) + list(APPEND TARGETS_DEP pnglite) + + set(PNGLITE_INCLUDEDIR ${PNGLITE_SRC_DIR}) + target_include_directories(pnglite PRIVATE ${ZLIB_INCLUDE_DIRS}) + + set(PNGLITE_DEP $) + set(PNGLITE_INCLUDE_DIRS ${PNGLITE_INCLUDEDIR}) + set(PNGLITE_LIBRARIES) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Pnglite DEFAULT_MSG PNGLITE_INCLUDEDIR) + set(PNGLITE_BUNDLED ON) +endif() diff --git a/cmake/FindSDL2.cmake b/cmake/FindSDL2.cmake new file mode 100644 index 000000000..e3a12ecbb --- /dev/null +++ b/cmake/FindSDL2.cmake @@ -0,0 +1,48 @@ +if(NOT PREFER_BUNDLED_LIBS) + set(CMAKE_MODULE_PATH ${ORIGINAL_CMAKE_MODULE_PATH}) + find_package(SDL2) + set(CMAKE_MODULE_PATH ${OWN_CMAKE_MODULE_PATH}) + if(SDL2_FOUND) + set(SDL2_BUNDLED OFF) + set(SDL2_DEP) + endif() +endif() + +if(NOT CMAKE_CROSSCOMPILING) + find_package(PkgConfig QUIET) + pkg_check_modules(PC_SDL2 sdl2) +endif() + +set_extra_dirs_lib(SDL2 sdl) +find_library(SDL2_LIBRARY + NAMES SDL2 + HINTS ${HINTS_SDL2_LIBDIR} ${SDL2_LIBDIR} ${PC_SDL2_LIBDIR} ${PC_SDL2_LIBRARY_DIRS} + PATHS ${PATHS_SDL2_LIBDIR} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} +) +set(CMAKE_FIND_FRAMEWORK FIRST) +set_extra_dirs_include(SDL2 sdl "${SDL2_LIBRARY}") +# Looking for 'SDL.h' directly might accidentally find a SDL 1 instead of SDL 2 +# installation. Look for a header file only present in SDL 2 instead. +find_path(SDL2_INCLUDEDIR SDL_assert.h + PATH_SUFFIXES SDL + HINTS ${HINTS_SDL2_INCLUDEDIR} ${SDL2_INCLUDE_DIRS} ${PC_SDL2_INCLUDEDIR} ${PC_SDL2_INCLUDE_DIRS} + PATHS ${PATHS_SDL2_INCLUDEDIR} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(SDL2 DEFAULT_MSG SDL2_LIBRARY SDL2_INCLUDEDIR) + +mark_as_advanced(SDL2_LIBRARY SDL2_INCLUDEDIR) + +if(SDL2_FOUND) + set(SDL2_LIBRARIES ${SDL2_LIBRARY}) + set(SDL2_INCLUDE_DIRS ${SDL2_INCLUDEDIR}) + + is_bundled(SDL2_BUNDLED "${SDL2_LIBRARY}") + if(SDL2_BUNDLED AND TARGET_OS STREQUAL "windows") + set(SDL2_COPY_FILES "${EXTRA_SDL2_LIBDIR}/SDL2.dll") + else() + set(SDL2_COPY_FILES) + endif() +endif() diff --git a/cmake/FindWavpack.cmake b/cmake/FindWavpack.cmake new file mode 100644 index 000000000..b7e855268 --- /dev/null +++ b/cmake/FindWavpack.cmake @@ -0,0 +1,52 @@ +if(NOT PREFER_BUNDLED_LIBS) + if(NOT CMAKE_CROSSCOMPILING) + find_package(PkgConfig QUIET) + pkg_check_modules(PC_WAVPACK wavpack) + endif() + + find_library(WAVPACK_LIBRARY + NAMES wavpack + HINTS ${PC_WAVPACK_LIBDIR} ${PC_WAVPACK_LIBRARY_DIRS} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} + ) + find_path(WAVPACK_INCLUDEDIR + NAMES wavpack.h + PATH_SUFFIXES wavpack + HINTS ${PC_WAVPACK_INCLUDEDIR} ${PC_WAVPACK_INCLUDE_DIRS} + ${CROSSCOMPILING_NO_CMAKE_SYSTEM_PATH} + ) + + mark_as_advanced(WAVPACK_LIBRARY WAVPACK_INCLUDEDIR) + + if(WAVPACK_LIBRARY AND WAVPACK_INCLUDEDIR) + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Wavpack DEFAULT_MSG WAVPACK_LIBRARY WAVPACK_INCLUDEDIR) + + set(WAVPACK_LIBRARIES ${WAVPACK_LIBRARY}) + set(WAVPACK_INCLUDE_DIRS ${WAVPACK_INCLUDEDIR}) + set(WAVPACK_BUNDLED OFF) + endif() +endif() + +if(NOT WAVPACK_FOUND) + set(WAVPACK_SRC_DIR src/engine/external/wavpack) + set_src(WAVPACK_SRC GLOB ${WAVPACK_SRC_DIR} + bits.c + float.c + metadata.c + unpack.c + wavpack.h + words.c + wputils.c + ) + add_library(wavpack EXCLUDE_FROM_ALL OBJECT ${WAVPACK_SRC}) + set(WAVPACK_DEP $) + set(WAVPACK_INCLUDEDIR ${WAVPACK_SRC_DIR}) + set(WAVPACK_INCLUDE_DIRS ${WAVPACK_INCLUDEDIR}) + + list(APPEND TARGETS_DEP wavpack) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Wavpack DEFAULT_MSG WAVPACK_INCLUDEDIR) + set(WAVPACK_BUNDLED ON) +endif() diff --git a/cmake/FindZLIB.cmake b/cmake/FindZLIB.cmake new file mode 100644 index 000000000..a8dfca4d3 --- /dev/null +++ b/cmake/FindZLIB.cmake @@ -0,0 +1,50 @@ +if(NOT PREFER_BUNDLED_LIBS) + set(CMAKE_MODULE_PATH ${ORIGINAL_CMAKE_MODULE_PATH}) + find_package(ZLIB) + set(CMAKE_MODULE_PATH ${OWN_CMAKE_MODULE_PATH}) + if(ZLIB_FOUND) + set(ZLIB_BUNDLED OFF) + set(ZLIB_DEP) + endif() +endif() + +if(NOT ZLIB_FOUND) + set(ZLIB_BUNDLED ON) + set(ZLIB_SRC_DIR src/engine/external/zlib) + set_src(ZLIB_SRC GLOB ${ZLIB_SRC_DIR} + adler32.c + compress.c + crc32.c + crc32.h + deflate.c + deflate.h + gzguts.h + infback.c + inffast.c + inffast.h + inffixed.h + inflate.c + inflate.h + inftrees.c + inftrees.h + trees.c + trees.h + uncompr.c + zconf.h + zlib.h + zutil.c + zutil.h + ) + add_library(zlib EXCLUDE_FROM_ALL OBJECT ${ZLIB_SRC}) + set(ZLIB_INCLUDEDIR ${ZLIB_SRC_DIR}) + target_include_directories(zlib PRIVATE ${ZLIB_INCLUDEDIR}) + + set(ZLIB_DEP $) + set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDEDIR}) + set(ZLIB_LIBRARIES) + + list(APPEND TARGETS_DEP zlib) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(ZLIB DEFAULT_MSG ZLIB_INCLUDEDIR) +endif() diff --git a/cmake/toolchains/darwin.toolchain b/cmake/toolchains/darwin.toolchain new file mode 100644 index 000000000..6d1d6eb3e --- /dev/null +++ b/cmake/toolchains/darwin.toolchain @@ -0,0 +1,11 @@ +set(CMAKE_SYSTEM_NAME Darwin) + +set(CMAKE_C_COMPILER o64-clang) +set(CMAKE_CXX_COMPILER o64-clang++) +set(CMAKE_INSTALL_NAME_TOOL x86_64-apple-darwin15-install_name_tool) +set(CMAKE_OTOOL x86_64-apple-darwin15-otool) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/cmake/toolchains/mingw32.toolchain b/cmake/toolchains/mingw32.toolchain new file mode 100644 index 000000000..c4c065b7e --- /dev/null +++ b/cmake/toolchains/mingw32.toolchain @@ -0,0 +1,10 @@ +set(CMAKE_SYSTEM_NAME Windows) + +set(CMAKE_C_COMPILER i686-w64-mingw32-gcc) +set(CMAKE_CXX_COMPILER i686-w64-mingw32-g++) +set(CMAKE_RC_COMPILER i686-w64-mingw32-windres) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/cmake/toolchains/mingw64.toolchain b/cmake/toolchains/mingw64.toolchain new file mode 100644 index 000000000..bec41e944 --- /dev/null +++ b/cmake/toolchains/mingw64.toolchain @@ -0,0 +1,10 @@ +set(CMAKE_SYSTEM_NAME Windows) + +set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) +set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++) +set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/configure.lua b/configure.lua new file mode 100644 index 000000000..b4d0a0676 --- /dev/null +++ b/configure.lua @@ -0,0 +1,501 @@ + +--[[@GROUP Configuration@END]]-- + +--[[@FUNCTION + TODO +@END]]-- +function NewConfig(on_configured_callback) + local config = {} + + config.OnConfigured = function(self) + return true + end + + if on_configured_callback then config.OnConfigured = on_configured_callback end + + config.options = {} + config.settings = NewSettings() + + config.NewSettings = function(self) + local s = NewSettings() + for _,v in pairs(self.options) do + v:Apply(s) + end + return s + end + + config.Add = function(self, o) + table.insert(self.options, o) + self[o.name] = o + end + + config.Print = function(self) + for k,v in pairs(self.options) do + print(v:FormatDisplay()) + end + end + + config.Save = function(self, filename) + print("saved configuration to '"..filename.."'") + local file = io.open(filename, "w") + + -- Define a little helper function to save options + local saver = {} + saver.file = file + + saver.line = function(self, str) + self.file:write(str .. "\n") + end + + saver.option = function(self, option, name) + local valuestr = "no" + if type(option[name]) == type(0) then + valuestr = option[name] + elseif type(option[name]) == type(true) then + valuestr = "false" + if option[name] then + valuestr = "true" + end + elseif type(option[name]) == type("") then + valuestr = "'"..option[name].."'" + else + error("option "..name.." have a value of type ".. type(option[name]).." that can't be saved") + end + self.file:write(option.name.."."..name.." = ".. valuestr.."\n") + end + + -- Save all the options + for k,v in pairs(self.options) do + v:Save(saver) + end + file:close() + end + + config.Load = function(self, filename) + local options_table = {} + local options_func = loadfile(filename, nil, options_table) + + if not options_func then + print("auto configuration") + self:Config(filename) + options_func = loadfile(filename, nil, options_table) + end + + if options_func then + -- Setup the options tables + for k,v in pairs(self.options) do + options_table[v.name] = {} + end + + -- this is to make sure that we get nice error messages when + -- someone sets an option that isn't valid. + local mt = {} + mt.__index = function(t, key) + local v = rawget(t, key) + if v ~= nil then return v end + error("there is no configuration option named '" .. key .. "'") + end + + setmetatable(options_table, mt) + + -- Process the options + options_func() + + -- Copy the options + for k,v in pairs(self.options) do + if options_table[v.name] then + for k2,v2 in pairs(options_table[v.name]) do + v[k2] = v2 + end + v.auto_detected = false + end + end + else + print("error: no '"..filename.."' found") + print("") + print("run 'bam config' to generate") + print("run 'bam config help' for configuration options") + print("") + os.exit(1) + end + end + + config.Config = function(self, filename) + print("") + print("configuration:") + if _bam_targets[1] == "print" then + self:Load(filename) + self:Print() + print("") + print("notes:") + self:OnConfigured() + print("") + else + self:Autodetect() + print("") + print("notes:") + if self:OnConfigured() then + self:Save(filename) + end + print("") + end + + end + + config.Autodetect = function(self) + for k,v in pairs(self.options) do + v:Check(self.settings) + print(v:FormatDisplay()) + self[v.name] = v + end + end + + config.PrintHelp = function(self) + print("options:") + for k,v in pairs(self.options) do + if v.PrintHelp then + v:PrintHelp() + end + end + end + + config.Finalize = function(self, filename) + if _bam_targets[0] == "config" then + if _bam_targets[1] == "help" then + self:PrintHelp() + os.exit(0) + end + + self:Config(filename) + + os.exit(0) + end + + self:Load(filename) + bam_update_globalstamp(filename) + end + + return config +end + + +-- Helper functions -------------------------------------- +function DefaultOptionDisplay(option) + if not option.value then return "no" end + if option.value == 1 or option.value == true then return "yes" end + return option.value +end + +function IsNegativeTerm(s) + if s == "no" then return true end + if s == "false" then return true end + if s == "off" then return true end + if s == "disable" then return true end + if s == "0" then return true end + return false +end + +function IsPositiveTerm(s) + if s == "yes" then return true end + if s == "true" then return true end + if s == "on" then return true end + if s == "enable" then return true end + if s == "1" then return true end + return false +end + +function MakeOption(name, value, check, save, display, printhelp) + local o = {} + o.name = name + o.value = value + o.Check = check + o.Save = save + o.auto_detected = true + o.FormatDisplay = function(self) + local a = "SET" + if self.auto_detected then a = "AUTO" end + return string.format("%-5s %-20s %s", a, self.name, self:Display()) + end + + o.Display = display + o.PrintHelp = printhelp + if o.Display == nil then o.Display = DefaultOptionDisplay end + return o +end + + +-- Test Compile C -------------------------------------- +function OptTestCompileC(name, source, compileoptions, desc) + local check = function(option, settings) + option.value = false + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif IsPositiveTerm(ScriptArgs[option.name]) then + option.value = true + else + error(ScriptArgs[option.name].." is not a valid value for option "..option.name) + end + option.auto_detected = false + else + if CTestCompile(settings, option.source, option.compileoptions) then + option.value = true + end + end + end + + local save = function(option, output) + output:option(option, "value") + end + + local printhelp = function(option) + print("\t"..option.name.."=on|off") + if option.desc then print("\t\t"..option.desc) end + end + + local o = MakeOption(name, false, check, save, nil, printhelp) + o.desc = desc + o.source = source + o.compileoptions = compileoptions + return o +end + + +-- OptToggle -------------------------------------- +function OptToggle(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif IsPositiveTerm(ScriptArgs[option.name]) then + option.value = true + else + error(ScriptArgs[option.name].." is not a valid value for option "..option.name) + end + end + end + + local save = function(option, output) + output:option(option, "value") + end + + local printhelp = function(option) + print("\t"..option.name.."=on|off") + if option.desc then print("\t\t"..option.desc) end + end + + local o = MakeOption(name, default_value, check, save, nil, printhelp) + o.desc = desc + return o +end + +-- OptInteger -------------------------------------- +function OptInteger(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + option.value = tonumber(ScriptArgs[option.name]) + end + end + + local save = function(option, output) + output:option(option, "value") + end + + local printhelp = function(option) + print("\t"..option.name.."=N") + if option.desc then print("\t\t"..option.desc) end + end + + local o = MakeOption(name, default_value, check, save, nil, printhelp) + o.desc = desc + return o +end + + +-- OptString -------------------------------------- +function OptString(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + option.value = ScriptArgs[option.name] + end + end + + local save = function(option, output) + output:option(option, "value") + end + + local printhelp = function(option) + print("\t"..option.name.."=STRING") + if option.desc then print("\t\t"..option.desc) end + end + + local o = MakeOption(name, default_value, check, save, nil, printhelp) + o.desc = desc + return o +end + +-- Find Compiler -------------------------------------- +--[[@FUNCTION + TODO +@END]]-- +function OptCCompiler(name, default_driver, default_c, default_cxx, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + -- set compile driver + option.driver = ScriptArgs[option.name] + + -- set c compiler + if ScriptArgs[option.name..".c"] then + option.c_compiler = ScriptArgs[option.name..".c"] + end + + -- set c+= compiler + if ScriptArgs[option.name..".cxx"] then + option.cxx_compiler = ScriptArgs[option.name..".cxx"] + end + + option.auto_detected = false + elseif option.driver then + -- no need todo anything if we have a driver + -- TODO: test if we can find the compiler + else + if ExecuteSilent("g++ -v") == 0 and ((arch ~= "amd64" and arch ~= "ia64") or CTestCompile(settings, "int main(){return 0;}", "-m64")) then + option.driver = "gcc" + elseif ExecuteSilent("cl") == 0 then + option.driver = "cl" + else + error("no c/c++ compiler found") + end + end + --setup_compiler(option.value) + end + + local apply = function(option, settings) + if option.driver == "cl" then + SetDriversCL(settings) + elseif option.driver == "gcc" then + SetDriversGCC(settings) + elseif option.driver == "clang" then + SetDriversClang(settings) + else + error(option.driver.." is not a known c/c++ compile driver") + end + + if option.c_compiler then settings.cc.c_compiler = option.c_compiler end + if option.cxx_compiler then settings.cc.cxx_compiler = option.cxx_compiler end + end + + local save = function(option, output) + output:option(option, "driver") + output:option(option, "c_compiler") + output:option(option, "cxx_compiler") + end + + local printhelp = function(option) + local a = "" + if option.desc then a = "for "..option.desc end + print("\t"..option.name.."=gcc|cl|clang") + print("\t\twhat c/c++ compile driver to use"..a) + print("\t"..option.name..".c=FILENAME") + print("\t\twhat c compiler executable to use"..a) + print("\t"..option.name..".cxx=FILENAME") + print("\t\twhat c++ compiler executable to use"..a) + end + + local display = function(option) + local s = option.driver + if option.c_compiler then s = s .. " c="..option.c_compiler end + if option.cxx_compiler then s = s .. " cxx="..option.cxx_compiler end + return s + end + + local o = MakeOption(name, nil, check, save, display, printhelp) + o.desc = desc + o.driver = false + o.c_compiler = false + o.cxx_compiler = false + + if default_driver then o.driver = default_driver end + if default_c then o.c_compiler = default_c end + if default_cxx then o.cxx_compiler = default_cxx end + + o.Apply = apply + return o +end + +-- Option Library -------------------------------------- +--[[@FUNCTION + TODO +@END]]-- +function OptLibrary(name, header, desc) + local check = function(option, settings) + option.value = false + option.include_path = false + + local function check_compile_include(filename, paths) + if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "") then + return "" + end + + for k,v in pairs(paths) do + if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "-I"..v) then + return v + end + end + + return false + end + + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif ScriptArgs[option.name] == "system" then + option.value = true + else + option.value = true + option.include_path = ScriptArgs[option.name] + end + option.auto_detected = false + else + option.include_path = check_compile_include(option.header, {}) + if option.include_path == false then + if option.required then + print(name.." library not found and is required") + error("required library not found") + end + else + option.value = true + option.include_path = false + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "include_path") + end + + local display = function(option) + if option.value then + if option.include_path then + return option.include_path + else + return "(in system path)" + end + else + return "not found" + end + end + + local printhelp = function(option) + print("\t"..option.name.."=disable|system|PATH") + if option.desc then print("\t\t"..option.desc) end + end + + local o = MakeOption(name, false, check, save, display, printhelp) + o.include_path = false + o.header = header + o.desc = desc + return o +end + diff --git a/datasrc/compile.py b/datasrc/compile.py new file mode 100644 index 000000000..d54db02cf --- /dev/null +++ b/datasrc/compile.py @@ -0,0 +1,327 @@ +import sys +from datatypes import * +import content +import network + +def create_enum_table(names, num): + lines = [] + lines += ["enum", "{"] + lines += ["\t%s=0,"%names[0]] + for name in names[1:]: + lines += ["\t%s,"%name] + lines += ["\t%s" % num, "};"] + return lines + +def create_flags_table(names): + lines = [] + lines += ["enum", "{"] + i = 0 + for name in names: + lines += ["\t%s = 1<<%d," % (name,i)] + i += 1 + lines += ["};"] + return lines + +def EmitEnum(names, num): + print("enum") + print("{") + print("\t%s=0," % names[0]) + for name in names[1:]: + print("\t%s," % name) + print("\t%s" % num) + print("};") + +def EmitFlags(names, num): + print("enum") + print("{") + i = 0 + for name in names: + print("\t%s = 1<<%d," % (name,i)) + i += 1 + print("};") + +gen_network_header = False +gen_network_source = False +gen_server_content_header = False +gen_server_content_source = False + +if "network_header" in sys.argv: gen_network_header = True +if "network_source" in sys.argv: gen_network_source = True +if "server_content_header" in sys.argv: gen_server_content_header = True +if "server_content_source" in sys.argv: gen_server_content_source = True + +if gen_server_content_header: + print("#ifndef SERVER_CONTENT_HEADER") + print("#define SERVER_CONTENT_HEADER") + + +if gen_server_content_header: + + # emit the type declarations + contentlines = open("datasrc/content.py", "rb").readlines() + order = [] + for line in contentlines: + line = line.strip() + if line[:6] == "class ".encode() and "(Struct)".encode() in line: + order += [line.split()[1].split("(".encode())[0].decode("ascii")] + for name in order: + EmitTypeDeclaration(content.__dict__[name]) + + # the container pointer + print('extern CDataContainer *g_pData;') + + # enums + EmitEnum(["IMAGE_%s"%i.name.value.upper() for i in content.container.images.items], "NUM_IMAGES") + EmitEnum(["ANIM_%s"%i.name.value.upper() for i in content.container.animations.items], "NUM_ANIMS") + EmitEnum(["SPRITE_%s"%i.name.value.upper() for i in content.container.sprites.items], "NUM_SPRITES") + +if gen_server_content_source: + if gen_server_content_source: + print('#include "server_data.h"') + EmitDefinition(content.container, "datacontainer") + print('CDataContainer *g_pData = &datacontainer;') + +# NETWORK +if gen_network_header: + + print("#ifndef GAME_GENERATED_PROTOCOL_H") + print("#define GAME_GENERATED_PROTOCOL_H") + print(network.RawHeader) + + for e in network.Enums: + for l in create_enum_table(["%s_%s"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): print(l) + print("") + + for e in network.Flags: + for l in create_flags_table(["%s_%s" % (e.name, v) for v in e.values]): print(l) + print("") + + for l in create_enum_table(["NETOBJ_INVALID"]+[o.enum_name for o in network.Objects], "NUM_NETOBJTYPES"): print(l) + print("") + for l in create_enum_table(["NETMSG_INVALID"]+[o.enum_name for o in network.Messages], "NUM_NETMSGTYPES"): print(l) + print("") + + for item in network.Objects + network.Messages: + for line in item.emit_declaration(): + print(line) + print("") + + EmitEnum(["SOUND_%s"%i.name.value.upper() for i in content.container.sounds.items], "NUM_SOUNDS") + EmitEnum(["WEAPON_%s"%i.name.value.upper() for i in content.container.weapons.id.items], "NUM_WEAPONS") + + print(""" + +class CNetObjHandler +{ + const char *m_pMsgFailedOn; + char m_aMsgData[1024]; + const char *m_pObjFailedOn; + int m_NumObjFailures; + bool CheckInt(const char *pErrorMsg, int Value, int Min, int Max); + bool CheckFlag(const char *pErrorMsg, int Value, int Mask); + + static const char *ms_apObjNames[]; + static int ms_aObjSizes[]; + static const char *ms_apMsgNames[]; + +public: + CNetObjHandler(); + + int ValidateObj(int Type, const void *pData, int Size); + const char *GetObjName(int Type) const; + int GetObjSize(int Type) const; + const char *FailedObjOn() const; + int NumObjFailures() const; + + const char *GetMsgName(int Type) const; + void *SecureUnpackMsg(int Type, CUnpacker *pUnpacker); + const char *FailedMsgOn() const; +}; + +""") + + print("#endif // GAME_GENERATED_PROTOCOL_H") + + +if gen_network_source: + # create names + lines = [] + + lines += ['#include '] + lines += ['#include '] + lines += ['#include "protocol.h"'] + + lines += ['CNetObjHandler::CNetObjHandler()'] + lines += ['{'] + lines += ['\tm_pMsgFailedOn = "";'] + lines += ['\tm_pObjFailedOn = "";'] + lines += ['\tm_NumObjFailures = 0;'] + lines += ['}'] + lines += [''] + lines += ['const char *CNetObjHandler::FailedObjOn() const { return m_pObjFailedOn; }'] + lines += ['int CNetObjHandler::NumObjFailures() const { return m_NumObjFailures; }'] + lines += ['const char *CNetObjHandler::FailedMsgOn() const { return m_pMsgFailedOn; }'] + lines += [''] + lines += [''] + lines += [''] + lines += [''] + + lines += ['static const int max_int = 0x7fffffff;'] + lines += [''] + + lines += ['bool CNetObjHandler::CheckInt(const char *pErrorMsg, int Value, int Min, int Max)'] + lines += ['{'] + lines += ['\tif(Value < Min || Value > Max) { m_pObjFailedOn = pErrorMsg; m_NumObjFailures++; return false; }'] + lines += ['\treturn true;'] + lines += ['}'] + lines += [''] + + lines += ['bool CNetObjHandler::CheckFlag(const char *pErrorMsg, int Value, int Mask)'] + lines += ['{'] + lines += ['\tif((Value&Mask) != Value) { m_pObjFailedOn = pErrorMsg; m_NumObjFailures++; return false; }'] + lines += ['\treturn true;'] + lines += ['}'] + lines += [''] + + lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"] + lines += ['\t"invalid",'] + lines += ['\t"%s",' % o.name for o in network.Objects] + lines += ['\t""', "};", ""] + + lines += ["int CNetObjHandler::ms_aObjSizes[] = {"] + lines += ['\t0,'] + lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects] + lines += ['\t0', "};", ""] + + + lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {'] + lines += ['\t"invalid",'] + for msg in network.Messages: + lines += ['\t"%s",' % msg.name] + lines += ['\t""'] + lines += ['};'] + lines += [''] + + lines += ['const char *CNetObjHandler::GetObjName(int Type) const'] + lines += ['{'] + lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return "(out of range)";'] + lines += ['\treturn ms_apObjNames[Type];'] + lines += ['};'] + lines += [''] + + lines += ['int CNetObjHandler::GetObjSize(int Type) const'] + lines += ['{'] + lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return 0;'] + lines += ['\treturn ms_aObjSizes[Type];'] + lines += ['};'] + lines += [''] + + + lines += ['const char *CNetObjHandler::GetMsgName(int Type) const'] + lines += ['{'] + lines += ['\tif(Type < 0 || Type >= NUM_NETMSGTYPES) return "(out of range)";'] + lines += ['\treturn ms_apMsgNames[Type];'] + lines += ['};'] + lines += [''] + + + for l in lines: + print(l) + + if 0: + for item in network.Objects: + for line in item.emit_validate(): + print(line) + print("") + + # create validate tables + lines = [] + lines += ['static int validate_invalid(void *data, int size) { return -1; }'] + lines += ["typedef int(*VALIDATEFUNC)(void *data, int size);"] + lines += ["static VALIDATEFUNC validate_funcs[] = {"] + lines += ['\tvalidate_invalid,'] + lines += ['\tvalidate_%s,' % o.name for o in network.Objects] + lines += ["\t0x0", "};", ""] + + lines += ["int netobj_validate(int type, void *data, int size)"] + lines += ["{"] + lines += ["\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;"] + lines += ["\treturn validate_funcs[type](data, size);"] + lines += ["};", ""] + + lines = [] + lines += ['int CNetObjHandler::ValidateObj(int Type, const void *pData, int Size)'] + lines += ['{'] + lines += ['\tswitch(Type)'] + lines += ['\t{'] + + for item in network.Objects: + base_item = None + if item.base: + base_item = next(i for i in network.Objects if i.name == item.base) + for line in item.emit_validate(base_item): + lines += ["\t" + line] + lines += ['\t'] + lines += ['\t}'] + lines += ['\treturn -1;'] + lines += ['};'] + lines += [''] + + #int Validate(int Type, void *pData, int Size); + + if 0: + for item in network.Messages: + for line in item.emit_unpack(): + print(line) + print("") + + lines += ['static void *secure_unpack_invalid(CUnpacker *pUnpacker) { return 0; }'] + lines += ['typedef void *(*SECUREUNPACKFUNC)(CUnpacker *pUnpacker);'] + lines += ['static SECUREUNPACKFUNC secure_unpack_funcs[] = {'] + lines += ['\tsecure_unpack_invalid,'] + for msg in network.Messages: + lines += ['\tsecure_unpack_%s,' % msg.name] + lines += ['\t0x0'] + lines += ['};'] + + # + lines += ['void *CNetObjHandler::SecureUnpackMsg(int Type, CUnpacker *pUnpacker)'] + lines += ['{'] + lines += ['\tm_pMsgFailedOn = 0;'] + lines += ['\tm_pObjFailedOn = 0;'] + lines += ['\tswitch(Type)'] + lines += ['\t{'] + + + for item in network.Messages: + for line in item.emit_unpack(): + lines += ["\t" + line] + lines += ['\t'] + + lines += ['\tdefault:'] + lines += ['\t\tm_pMsgFailedOn = "(type out of range)";'] + lines += ['\t\tbreak;'] + lines += ['\t}'] + lines += ['\t'] + lines += ['\tif(pUnpacker->Error())'] + lines += ['\t\tm_pMsgFailedOn = "(unpack error)";'] + lines += ['\t'] + lines += ['\tif(m_pMsgFailedOn || m_pObjFailedOn) {'] + lines += ['\t\tif(!m_pMsgFailedOn)'] + lines += ['\t\t\tm_pMsgFailedOn = "";'] + lines += ['\t\tif(!m_pObjFailedOn)'] + lines += ['\t\t\tm_pObjFailedOn = "";'] + lines += ['\t\treturn 0;'] + lines += ['\t}'] + lines += ['\tm_pMsgFailedOn = "";'] + lines += ['\tm_pObjFailedOn = "";'] + lines += ['\treturn m_aMsgData;'] + lines += ['};'] + lines += [''] + + + for l in lines: + print(l) + +if gen_server_content_header: + print("#endif") diff --git a/datasrc/content.py b/datasrc/content.py new file mode 100644 index 000000000..c1e1dd182 --- /dev/null +++ b/datasrc/content.py @@ -0,0 +1,686 @@ +from datatypes import * + +class Sound(Struct): + def __init__(self, filename=""): + Struct.__init__(self, "CDataSound") + self.id = Int(0) + self.filename = String(filename) + +class SoundSet(Struct): + def __init__(self, name="", files=[]): + Struct.__init__(self, "CDataSoundset") + self.name = String(name) + self.sounds = Array(Sound()) + self.last = Int(-1) + for name in files: + self.sounds.Add(Sound(name)) + +class Image(Struct): + def __init__(self, name="", filename="", linear_mapping=0): + Struct.__init__(self, "CDataImage") + self.name = String(name) + self.filename = String(filename) + self.flag = Int(linear_mapping) + self.id = Int(-1) + +class SpriteSet(Struct): + def __init__(self, name="", image=None, gridx=0, gridy=0): + Struct.__init__(self, "CDataSpriteset") + self.image = Pointer(Image, image) # TODO + self.gridx = Int(gridx) + self.gridy = Int(gridy) + +class Sprite(Struct): + def __init__(self, name="", Set=None, x=0, y=0, w=0, h=0): + Struct.__init__(self, "CDataSprite") + self.name = String(name) + self.set = Pointer(SpriteSet, Set) # TODO + self.x = Int(x) + self.y = Int(y) + self.w = Int(w) + self.h = Int(h) + +class Pickup(Struct): + def __init__(self, name="", respawntime=15, spawndelay=0): + Struct.__init__(self, "CDataPickupspec") + self.name = String(name) + self.respawntime = Int(respawntime) + self.spawndelay = Int(spawndelay) + +class AnimKeyframe(Struct): + def __init__(self, time=0, x=0, y=0, angle=0): + Struct.__init__(self, "CAnimKeyframe") + self.time = Float(time) + self.x = Float(x) + self.y = Float(y) + self.angle = Float(angle) + +class AnimSequence(Struct): + def __init__(self): + Struct.__init__(self, "CAnimSequence") + self.frames = Array(AnimKeyframe()) + +class Animation(Struct): + def __init__(self, name=""): + Struct.__init__(self, "CAnimation") + self.name = String(name) + self.body = AnimSequence() + self.back_foot = AnimSequence() + self.front_foot = AnimSequence() + self.attach = AnimSequence() + +class WeaponSpec(Struct): + def __init__(self, container=None, name=""): + Struct.__init__(self, "CDataWeaponspec") + self.name = String(name) + self.sprite_body = Pointer(Sprite, Sprite()) + self.sprite_cursor = Pointer(Sprite, Sprite()) + self.sprite_proj = Pointer(Sprite, Sprite()) + self.sprite_muzzles = Array(Pointer(Sprite, Sprite())) + self.visual_size = Int(96) + + self.firedelay = Int(500) + self.maxammo = Int(10) + self.ammoregentime = Int(0) + self.damage = Int(1) + + self.offsetx = Float(0) + self.offsety = Float(0) + self.muzzleoffsetx = Float(0) + self.muzzleoffsety = Float(0) + self.muzzleduration = Float(5) + + # dig out sprites if we have a container + if container: + for sprite in container.sprites.items: + if sprite.name.value == "weapon_"+name+"_body": self.sprite_body.Set(sprite) + elif sprite.name.value == "weapon_"+name+"_cursor": self.sprite_cursor.Set(sprite) + elif sprite.name.value == "weapon_"+name+"_proj": self.sprite_proj.Set(sprite) + elif "weapon_"+name+"_muzzle" in sprite.name.value: + self.sprite_muzzles.Add(Pointer(Sprite, sprite)) + +class Weapon_Hammer(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecHammer") + self.base = Pointer(WeaponSpec, WeaponSpec()) + +class Weapon_Gun(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecGun") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(1.25) + self.speed = Float(2200) + self.lifetime = Float(2.0) + +class Weapon_Shotgun(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecShotgun") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(1.25) + self.speed = Float(2200) + self.speeddiff = Float(0.8) + self.lifetime = Float(0.25) + +class Weapon_Grenade(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecGrenade") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(7.0) + self.speed = Float(1000) + self.lifetime = Float(2.0) + +class Weapon_Laser(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecLaser") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.reach = Float(800.0) + self.bounce_delay = Int(150) + self.bounce_num = Int(1) + self.bounce_cost = Float(0) + +class Weapon_Ninja(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecNinja") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.duration = Int(15000) + self.movetime = Int(200) + self.velocity = Int(50) + +class Weapons(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecs") + self.hammer = Weapon_Hammer() + self.gun = Weapon_Gun() + self.shotgun = Weapon_Shotgun() + self.grenade = Weapon_Grenade() + self.laser = Weapon_Laser() + self.ninja = Weapon_Ninja() + self.id = Array(WeaponSpec()) + +class Explosion(Struct): + def __init__(self): + Struct.__init__(self, "CDataExplosion") + self.radius = Float(135) + self.max_force = Float(12) + +class DataContainer(Struct): + def __init__(self): + Struct.__init__(self, "CDataContainer") + self.sounds = Array(SoundSet()) + self.images = Array(Image()) + self.pickups = Array(Pickup()) + self.spritesets = Array(SpriteSet()) + self.sprites = Array(Sprite()) + self.animations = Array(Animation()) + self.weapons = Weapons() + self.explosion = Explosion() + +def FileList(format, num): + return [format%(x+1) for x in range(0,num)] + +container = DataContainer() +container.sounds.Add(SoundSet("gun_fire", FileList("audio/wp_gun_fire-%02d.wv", 3))) +container.sounds.Add(SoundSet("shotgun_fire", FileList("audio/wp_shotty_fire-%02d.wv", 3))) + +container.sounds.Add(SoundSet("grenade_fire", FileList("audio/wp_flump_launch-%02d.wv", 3))) +container.sounds.Add(SoundSet("hammer_fire", FileList("audio/wp_hammer_swing-%02d.wv", 3))) +container.sounds.Add(SoundSet("hammer_hit", FileList("audio/wp_hammer_hit-%02d.wv", 3))) +container.sounds.Add(SoundSet("ninja_fire", FileList("audio/wp_ninja_attack-%02d.wv", 3))) +container.sounds.Add(SoundSet("grenade_explode", FileList("audio/wp_flump_explo-%02d.wv", 3))) +container.sounds.Add(SoundSet("ninja_hit", FileList("audio/wp_ninja_hit-%02d.wv", 3))) +container.sounds.Add(SoundSet("laser_fire", FileList("audio/wp_laser_fire-%02d.wv", 3))) +container.sounds.Add(SoundSet("laser_bounce", FileList("audio/wp_laser_bnce-%02d.wv", 3))) +container.sounds.Add(SoundSet("weapon_switch", FileList("audio/wp_switch-%02d.wv", 3))) + +container.sounds.Add(SoundSet("player_pain_short", FileList("audio/vo_teefault_pain_short-%02d.wv", 12))) +container.sounds.Add(SoundSet("player_pain_long", FileList("audio/vo_teefault_pain_long-%02d.wv", 2))) + +container.sounds.Add(SoundSet("body_land", FileList("audio/foley_land-%02d.wv", 4))) +container.sounds.Add(SoundSet("player_airjump", FileList("audio/foley_dbljump-%02d.wv", 3))) +container.sounds.Add(SoundSet("player_jump", FileList("audio/foley_foot_left-%02d.wv", 4) + FileList("audio/foley_foot_right-%02d.wv", 4))) +container.sounds.Add(SoundSet("player_die", FileList("audio/foley_body_splat-%02d.wv", 3))) +container.sounds.Add(SoundSet("player_spawn", FileList("audio/vo_teefault_spawn-%02d.wv", 7))) +container.sounds.Add(SoundSet("player_skid", FileList("audio/sfx_skid-%02d.wv", 4))) +container.sounds.Add(SoundSet("tee_cry", FileList("audio/vo_teefault_cry-%02d.wv", 2))) + +container.sounds.Add(SoundSet("hook_loop", FileList("audio/hook_loop-%02d.wv", 2))) + +container.sounds.Add(SoundSet("hook_attach_ground", FileList("audio/hook_attach-%02d.wv", 3))) +container.sounds.Add(SoundSet("hook_attach_player", FileList("audio/foley_body_impact-%02d.wv", 3))) +container.sounds.Add(SoundSet("hook_noattach", FileList("audio/hook_noattach-%02d.wv", 2))) +container.sounds.Add(SoundSet("pickup_health", FileList("audio/sfx_pickup_hrt-%02d.wv", 2))) +container.sounds.Add(SoundSet("pickup_armor", FileList("audio/sfx_pickup_arm-%02d.wv", 4))) + +container.sounds.Add(SoundSet("pickup_grenade", ["audio/sfx_pickup_launcher.wv"])) +container.sounds.Add(SoundSet("pickup_shotgun", ["audio/sfx_pickup_sg.wv"])) +container.sounds.Add(SoundSet("pickup_ninja", ["audio/sfx_pickup_ninja.wv"])) +container.sounds.Add(SoundSet("weapon_spawn", FileList("audio/sfx_spawn_wpn-%02d.wv", 3))) +container.sounds.Add(SoundSet("weapon_noammo", FileList("audio/wp_noammo-%02d.wv", 5))) + +container.sounds.Add(SoundSet("hit", FileList("audio/sfx_hit_weak-%02d.wv", 2))) + +container.sounds.Add(SoundSet("chat_server", ["audio/sfx_msg-server.wv"])) +container.sounds.Add(SoundSet("chat_client", ["audio/sfx_msg-client.wv"])) +container.sounds.Add(SoundSet("chat_highlight", ["audio/sfx_msg-highlight.wv"])) +container.sounds.Add(SoundSet("ctf_drop", ["audio/sfx_ctf_drop.wv"])) +container.sounds.Add(SoundSet("ctf_return", ["audio/sfx_ctf_rtn.wv"])) +container.sounds.Add(SoundSet("ctf_grab_pl", ["audio/sfx_ctf_grab_pl.wv"])) +container.sounds.Add(SoundSet("ctf_grab_en", ["audio/sfx_ctf_grab_en.wv"])) +container.sounds.Add(SoundSet("ctf_capture", ["audio/sfx_ctf_cap_pl.wv"])) + +container.sounds.Add(SoundSet("menu", ["audio/music_menu.wv"])) + +image_null = Image("null", "") +image_particles = Image("particles", "particles.png") +image_game = Image("game", "game.png") +image_browseicons = Image("browseicons", "ui/icons/browse.png", 1) +image_browsericon = Image("browser", "ui/icons/browser.png", 1) +image_emoticons = Image("emoticons", "emoticons.png") +image_demobuttons = Image("demobuttons", "ui/demo_buttons.png", 1) +image_fileicons = Image("fileicons", "ui/file_icons.png", 1) +image_guibuttons = Image("guibuttons", "ui/gui_buttons.png", 1) +image_guiicons = Image("guiicons", "ui/gui_icons.png", 1) +image_menuicons = Image("menuicons", "ui/icons/menu.png", 1) +image_soundicons = Image("soundicons", "ui/sound_icons.png", 1) +image_toolicons = Image("toolicons", "ui/icons/tools.png", 1) +image_arrowicons = Image("arrowicons", "ui/icons/arrows.png", 1) +image_friendicons = Image("friendicons", "ui/icons/friend.png", 1) +image_networkicons = Image("networkicons", "ui/icons/network.png", 1) +image_levelicons = Image("levelicons", "ui/icons/level.png", 1) +image_sidebaricons = Image("sidebaricons", "ui/icons/sidebar.png", 1) +image_chatwhisper = Image("chatwhisper", "ui/icons/chat_whisper.png", 1) +image_timerclock = Image("timerclock", "ui/icons/timer_clock.png", 1) + +container.images.Add(image_null) +container.images.Add(image_game) +container.images.Add(Image("deadtee", "deadtee.png")) +container.images.Add(image_particles) +container.images.Add(Image("cursor", "ui/gui_cursor.png")) +container.images.Add(Image("banner", "ui/gui_logo.png")) +container.images.Add(image_emoticons) +container.images.Add(image_browseicons) +container.images.Add(image_browsericon) +container.images.Add(Image("console_bg", "ui/console.png")) +container.images.Add(Image("console_bar", "ui/console_bar.png")) +container.images.Add(image_demobuttons) +container.images.Add(image_fileicons) +container.images.Add(image_guibuttons) +container.images.Add(image_guiicons) +container.images.Add(Image("no_skinpart", "ui/no_skinpart.png")) +container.images.Add(image_menuicons) +container.images.Add(image_soundicons) +container.images.Add(image_toolicons) +container.images.Add(image_arrowicons) +container.images.Add(image_friendicons) +container.images.Add(image_networkicons) +container.images.Add(image_levelicons) +container.images.Add(image_sidebaricons) +container.images.Add(image_chatwhisper) +container.images.Add(Image("raceflag", "race_flag.png")) +container.images.Add(image_timerclock) + +container.pickups.Add(Pickup("health")) +container.pickups.Add(Pickup("armor")) +container.pickups.Add(Pickup("grenade")) +container.pickups.Add(Pickup("shotgun")) +container.pickups.Add(Pickup("laser")) +container.pickups.Add(Pickup("ninja", 90, 90)) +container.pickups.Add(Pickup("gun")) +container.pickups.Add(Pickup("hammer")) + +set_particles = SpriteSet("particles", image_particles, 8, 8) +set_game = SpriteSet("game", image_game, 32, 16) +set_tee_body = SpriteSet("tee_body", image_null, 2, 2) +set_tee_markings = SpriteSet("tee_markings", image_null, 1, 1) +set_tee_decoration = SpriteSet("tee_decoration", image_null, 2, 1) +set_tee_hands = SpriteSet("tee_hands", image_null, 2, 1) +set_tee_feet = SpriteSet("tee_feet", image_null, 2, 1) +set_tee_eyes = SpriteSet("tee_eyes", image_null, 2, 4) +set_tee_hats = SpriteSet("tee_hats", image_null, 1, 4) +set_tee_bot = SpriteSet("tee_bot", image_null, 12, 5) +set_browseicons = SpriteSet("browseicons", image_browseicons, 4, 2) +set_browsericon = SpriteSet("browsericon", image_browsericon, 1, 2) +set_emoticons = SpriteSet("emoticons", image_emoticons, 4, 4) +set_demobuttons = SpriteSet("demobuttons", image_demobuttons, 5, 1) +set_fileicons = SpriteSet("fileicons", image_fileicons, 8, 1) +set_guibuttons = SpriteSet("guibuttons", image_guibuttons, 12, 4) +set_guiicons = SpriteSet("guiicons", image_guiicons, 8, 2) +set_menuicons = SpriteSet("menuicons", image_menuicons, 4, 4) +set_toolicons = SpriteSet("toolicons", image_toolicons, 4, 2) +set_soundicons = SpriteSet("guiicons", image_soundicons, 1, 2) +set_arrowicons = SpriteSet("arrowicons", image_arrowicons, 4, 3) +set_friendicons = SpriteSet("friendicons", image_friendicons, 2, 2) +set_networkicons = SpriteSet("networkicons", image_networkicons, 1, 2) +set_levelicons = SpriteSet("levelicons", image_levelicons, 4, 4) +set_sidebaricons = SpriteSet("sidebaricons", image_sidebaricons, 4, 2) +set_timerclock = SpriteSet("timerclock", image_timerclock, 1, 2) + +container.spritesets.Add(set_particles) +container.spritesets.Add(set_game) +container.spritesets.Add(set_tee_body) +container.spritesets.Add(set_tee_markings) +container.spritesets.Add(set_tee_decoration) +container.spritesets.Add(set_tee_hands) +container.spritesets.Add(set_tee_feet) +container.spritesets.Add(set_tee_eyes) +container.spritesets.Add(set_tee_hats) +container.spritesets.Add(set_tee_bot) +container.spritesets.Add(set_browseicons) +container.spritesets.Add(set_emoticons) +container.spritesets.Add(set_demobuttons) +container.spritesets.Add(set_fileicons) +container.spritesets.Add(set_guibuttons) +container.spritesets.Add(set_guiicons) +container.spritesets.Add(set_menuicons) +container.spritesets.Add(set_soundicons) +container.spritesets.Add(set_toolicons) +container.spritesets.Add(set_arrowicons) +container.spritesets.Add(set_friendicons) +container.spritesets.Add(set_networkicons) +container.spritesets.Add(set_levelicons) +container.spritesets.Add(set_sidebaricons) +container.spritesets.Add(set_timerclock) +container.spritesets.Add(set_browsericon) + + +container.sprites.Add(Sprite("part_slice", set_particles, 0,0,1,1)) +container.sprites.Add(Sprite("part_ball", set_particles, 1,0,1,1)) +container.sprites.Add(Sprite("part_splat01", set_particles, 2,0,1,1)) +container.sprites.Add(Sprite("part_splat02", set_particles, 3,0,1,1)) +container.sprites.Add(Sprite("part_splat03", set_particles, 4,0,1,1)) + +container.sprites.Add(Sprite("part_smoke", set_particles, 0,1,1,1)) +container.sprites.Add(Sprite("part_shell", set_particles, 0,2,2,2)) +container.sprites.Add(Sprite("part_expl01", set_particles, 0,4,4,4)) +container.sprites.Add(Sprite("part_airjump", set_particles, 2,2,2,2)) +container.sprites.Add(Sprite("part_hit01", set_particles, 4,1,2,2)) + +container.sprites.Add(Sprite("health_full", set_game, 21,0,2,2)) +container.sprites.Add(Sprite("health_empty", set_game, 23,0,2,2)) +container.sprites.Add(Sprite("armor_full", set_game, 21,2,2,2)) +container.sprites.Add(Sprite("armor_empty", set_game, 23,2,2,2)) + +container.sprites.Add(Sprite("star1", set_game, 15,0,2,2)) +container.sprites.Add(Sprite("star2", set_game, 17,0,2,2)) +container.sprites.Add(Sprite("star3", set_game, 19,0,2,2)) + +container.sprites.Add(Sprite("part1", set_game, 6,0,1,1)) +container.sprites.Add(Sprite("part2", set_game, 6,1,1,1)) +container.sprites.Add(Sprite("part3", set_game, 7,0,1,1)) +container.sprites.Add(Sprite("part4", set_game, 7,1,1,1)) +container.sprites.Add(Sprite("part5", set_game, 8,0,1,1)) +container.sprites.Add(Sprite("part6", set_game, 8,1,1,1)) +container.sprites.Add(Sprite("part7", set_game, 9,0,2,2)) +container.sprites.Add(Sprite("part8", set_game, 11,0,2,2)) +container.sprites.Add(Sprite("part9", set_game, 13,0,2,2)) + +container.sprites.Add(Sprite("weapon_gun_body", set_game, 2,4,4,2)) +container.sprites.Add(Sprite("weapon_gun_cursor", set_game, 0,4,2,2)) +container.sprites.Add(Sprite("weapon_gun_proj", set_game, 6,4,2,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle1", set_game, 8,4,3,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle2", set_game, 12,4,3,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle3", set_game, 16,4,3,2)) + +container.sprites.Add(Sprite("weapon_shotgun_body", set_game, 2,6,8,2)) +container.sprites.Add(Sprite("weapon_shotgun_cursor", set_game, 0,6,2,2)) +container.sprites.Add(Sprite("weapon_shotgun_proj", set_game, 10,6,2,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle1", set_game, 12,6,3,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle2", set_game, 16,6,3,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle3", set_game, 20,6,3,2)) + +container.sprites.Add(Sprite("weapon_grenade_body", set_game, 2,8,7,2)) +container.sprites.Add(Sprite("weapon_grenade_cursor", set_game, 0,8,2,2)) +container.sprites.Add(Sprite("weapon_grenade_proj", set_game, 10,8,2,2)) + +container.sprites.Add(Sprite("weapon_hammer_body", set_game, 2,1,4,3)) +container.sprites.Add(Sprite("weapon_hammer_cursor", set_game, 0,0,2,2)) +container.sprites.Add(Sprite("weapon_hammer_proj", set_game, 0,0,0,0)) + +container.sprites.Add(Sprite("weapon_ninja_body", set_game, 2,10,8,2)) +container.sprites.Add(Sprite("weapon_ninja_cursor", set_game, 0,10,2,2)) +container.sprites.Add(Sprite("weapon_ninja_proj", set_game, 0,0,0,0)) + +container.sprites.Add(Sprite("weapon_laser_body", set_game, 2,12,7,3)) +container.sprites.Add(Sprite("weapon_laser_cursor", set_game, 0,12,2,2)) +container.sprites.Add(Sprite("weapon_laser_proj", set_game, 10,12,2,2)) + +container.sprites.Add(Sprite("hook_chain", set_game, 2,0,1,1)) +container.sprites.Add(Sprite("hook_head", set_game, 3,0,2,1)) + +container.sprites.Add(Sprite("weapon_ninja_muzzle1", set_game, 25,0,7,4)) +container.sprites.Add(Sprite("weapon_ninja_muzzle2", set_game, 25,4,7,4)) +container.sprites.Add(Sprite("weapon_ninja_muzzle3", set_game, 25,8,7,4)) + +container.sprites.Add(Sprite("pickup_health", set_game, 10,2,2,2)) +container.sprites.Add(Sprite("pickup_armor", set_game, 12,2,2,2)) +container.sprites.Add(Sprite("pickup_grenade", set_game, 2,8,7,2)) +container.sprites.Add(Sprite("pickup_shotgun", set_game, 2,6,8,2)) +container.sprites.Add(Sprite("pickup_laser", set_game, 2,12,7,3)) +container.sprites.Add(Sprite("pickup_ninja", set_game, 2,10,8,2)) +container.sprites.Add(Sprite("pickup_gun", set_game, 2,4,4,2)) +container.sprites.Add(Sprite("pickup_hammer", set_game, 2,1,4,3)) + +container.sprites.Add(Sprite("flag_blue", set_game, 12,8,4,8)) +container.sprites.Add(Sprite("flag_red", set_game, 16,8,4,8)) + +container.sprites.Add(Sprite("ninja_bar_full_left", set_game, 21,4,1,2)) +container.sprites.Add(Sprite("ninja_bar_full", set_game, 22,4,1,2)) +container.sprites.Add(Sprite("ninja_bar_empty", set_game, 23,4,1,2)) +container.sprites.Add(Sprite("ninja_bar_empty_right", set_game, 24,4,1,2)) + +container.sprites.Add(Sprite("tee_body_outline", set_tee_body, 0,0,1,1)) +container.sprites.Add(Sprite("tee_body", set_tee_body, 1,0,1,1)) +container.sprites.Add(Sprite("tee_body_shadow", set_tee_body, 0,1,1,1)) +container.sprites.Add(Sprite("tee_body_upper_outline", set_tee_body, 1,1,1,1)) + +container.sprites.Add(Sprite("tee_marking", set_tee_markings, 0,0,1,1)) + +container.sprites.Add(Sprite("tee_decoration", set_tee_decoration, 0,0,1,1)) +container.sprites.Add(Sprite("tee_decoration_outline", set_tee_decoration, 1,0,1,1)) + +container.sprites.Add(Sprite("tee_hand", set_tee_hands, 0,0,1,1)) +container.sprites.Add(Sprite("tee_hand_outline", set_tee_hands, 1,0,1,1)) + +container.sprites.Add(Sprite("tee_foot", set_tee_feet, 0,0,1,1)) +container.sprites.Add(Sprite("tee_foot_outline", set_tee_feet, 1,0,1,1)) + +container.sprites.Add(Sprite("tee_eyes_normal", set_tee_eyes, 0,0,1,1)) +container.sprites.Add(Sprite("tee_eyes_angry", set_tee_eyes, 1,0,1,1)) +container.sprites.Add(Sprite("tee_eyes_pain", set_tee_eyes, 0,1,1,1)) +container.sprites.Add(Sprite("tee_eyes_happy", set_tee_eyes, 1,1,1,1)) +container.sprites.Add(Sprite("tee_eyes_surprise", set_tee_eyes, 0,2,1,1)) + +container.sprites.Add(Sprite("tee_hats_top1", set_tee_hats, 0,0,1,1)) +container.sprites.Add(Sprite("tee_hats_top2", set_tee_hats, 0,1,1,1)) +container.sprites.Add(Sprite("tee_hats_side1", set_tee_hats, 0,2,1,1)) +container.sprites.Add(Sprite("tee_hats_side2", set_tee_hats, 0,3,1,1)) + +container.sprites.Add(Sprite("tee_bot_glow", set_tee_bot, 0,0,4,4)) +container.sprites.Add(Sprite("tee_bot_foreground", set_tee_bot, 4,0,4,4)) +container.sprites.Add(Sprite("tee_bot_background", set_tee_bot, 8,0,4,4)) + +container.sprites.Add(Sprite("oop", set_emoticons, 0, 0, 1, 1)) +container.sprites.Add(Sprite("exclamation", set_emoticons, 1, 0, 1, 1)) +container.sprites.Add(Sprite("hearts", set_emoticons, 2, 0, 1, 1)) +container.sprites.Add(Sprite("drop", set_emoticons, 3, 0, 1, 1)) +container.sprites.Add(Sprite("dotdot", set_emoticons, 0, 1, 1, 1)) +container.sprites.Add(Sprite("music", set_emoticons, 1, 1, 1, 1)) +container.sprites.Add(Sprite("sorry", set_emoticons, 2, 1, 1, 1)) +container.sprites.Add(Sprite("ghost", set_emoticons, 3, 1, 1, 1)) +container.sprites.Add(Sprite("sushi", set_emoticons, 0, 2, 1, 1)) +container.sprites.Add(Sprite("splattee", set_emoticons, 1, 2, 1, 1)) +container.sprites.Add(Sprite("deviltee", set_emoticons, 2, 2, 1, 1)) +container.sprites.Add(Sprite("zomg", set_emoticons, 3, 2, 1, 1)) +container.sprites.Add(Sprite("zzz", set_emoticons, 0, 3, 1, 1)) +container.sprites.Add(Sprite("wtf", set_emoticons, 1, 3, 1, 1)) +container.sprites.Add(Sprite("eyes", set_emoticons, 2, 3, 1, 1)) +container.sprites.Add(Sprite("question", set_emoticons, 3, 3, 1, 1)) + +container.sprites.Add(Sprite("browse_lock_a", set_browseicons, 0,0,1,1)) +container.sprites.Add(Sprite("browse_lock_b", set_browseicons, 0,1,1,1)) +container.sprites.Add(Sprite("browse_unpure_a", set_browseicons, 1,0,1,1)) +container.sprites.Add(Sprite("browse_unpure_b", set_browseicons, 1,1,1,1)) +container.sprites.Add(Sprite("browse_star_a", set_browseicons, 2,0,1,1)) +container.sprites.Add(Sprite("browse_star_b", set_browseicons, 2,1,1,1)) +container.sprites.Add(Sprite("browse_heart_a", set_browseicons, 3,0,1,1)) +container.sprites.Add(Sprite("browse_heart_b", set_browseicons, 3,1,1,1)) + +container.sprites.Add(Sprite("demobutton_play", set_demobuttons, 0,0,1,1)) +container.sprites.Add(Sprite("demobutton_pause", set_demobuttons, 1,0,1,1)) +container.sprites.Add(Sprite("demobutton_stop", set_demobuttons, 2,0,1,1)) +container.sprites.Add(Sprite("demobutton_slower", set_demobuttons, 3,0,1,1)) +container.sprites.Add(Sprite("demobutton_faster", set_demobuttons, 4,0,1,1)) + +container.sprites.Add(Sprite("file_demo1", set_fileicons, 0,0,1,1)) +container.sprites.Add(Sprite("file_demo2", set_fileicons, 1,0,1,1)) +container.sprites.Add(Sprite("file_folder", set_fileicons, 2,0,1,1)) +container.sprites.Add(Sprite("file_map1", set_fileicons, 5,0,1,1)) +container.sprites.Add(Sprite("file_map2", set_fileicons, 6,0,1,1)) + +container.sprites.Add(Sprite("guibutton_off", set_guibuttons, 0,0,4,4)) +container.sprites.Add(Sprite("guibutton_on", set_guibuttons, 4,0,4,4)) +container.sprites.Add(Sprite("guibutton_hover", set_guibuttons, 8,0,4,4)) + +container.sprites.Add(Sprite("guiicon_mute", set_guiicons, 0,0,4,2)) +container.sprites.Add(Sprite("guiicon_friend", set_guiicons, 4,0,4,2)) + +container.sprites.Add(Sprite("menu_checkbox_active", set_menuicons, 0,0,1,1)) +container.sprites.Add(Sprite("menu_checkbox_inactive", set_menuicons, 0,1,1,1)) +container.sprites.Add(Sprite("menu_checkbox_hover", set_menuicons, 0,2,1,1)) +container.sprites.Add(Sprite("menu_collapsed", set_menuicons, 1,0,1,1)) +container.sprites.Add(Sprite("menu_expanded", set_menuicons, 1,1,1,1)) + +container.sprites.Add(Sprite("soundicon_on", set_soundicons, 0,0,1,1)) +container.sprites.Add(Sprite("soundicon_mute", set_soundicons, 0,1,1,1)) + +container.sprites.Add(Sprite("tool_up_a", set_toolicons, 0,0,1,1)) +container.sprites.Add(Sprite("tool_up_b", set_toolicons, 0,1,1,1)) +container.sprites.Add(Sprite("tool_down_a", set_toolicons, 1,0,1,1)) +container.sprites.Add(Sprite("tool_down_b", set_toolicons, 1,1,1,1)) +container.sprites.Add(Sprite("tool_edit_a", set_toolicons, 2,0,1,1)) +container.sprites.Add(Sprite("tool_edit_b", set_toolicons, 2,1,1,1)) +container.sprites.Add(Sprite("tool_x_a", set_toolicons, 3,0,1,1)) +container.sprites.Add(Sprite("tool_x_b", set_toolicons, 3,1,1,1)) + +container.sprites.Add(Sprite("arrow_left_a", set_arrowicons, 0,0,1,1)) +container.sprites.Add(Sprite("arrow_left_b", set_arrowicons, 0,1,1,1)) +container.sprites.Add(Sprite("arrow_left_c", set_arrowicons, 0,2,1,1)) +container.sprites.Add(Sprite("arrow_up_a", set_arrowicons, 1,0,1,1)) +container.sprites.Add(Sprite("arrow_up_b", set_arrowicons, 1,1,1,1)) +container.sprites.Add(Sprite("arrow_up_c", set_arrowicons, 1,2,1,1)) +container.sprites.Add(Sprite("arrow_right_a", set_arrowicons, 2,0,1,1)) +container.sprites.Add(Sprite("arrow_right_b", set_arrowicons, 2,1,1,1)) +container.sprites.Add(Sprite("arrow_right_c", set_arrowicons, 2,2,1,1)) +container.sprites.Add(Sprite("arrow_down_a", set_arrowicons, 3,0,1,1)) +container.sprites.Add(Sprite("arrow_down_b", set_arrowicons, 3,1,1,1)) +container.sprites.Add(Sprite("arrow_down_c", set_arrowicons, 3,2,1,1)) + +container.sprites.Add(Sprite("friend_plus_a", set_friendicons, 0,0,1,1)) +container.sprites.Add(Sprite("friend_plus_b", set_friendicons, 0,1,1,1)) +container.sprites.Add(Sprite("friend_x_a", set_friendicons, 1,0,1,1)) +container.sprites.Add(Sprite("friend_x_b", set_friendicons, 1,1,1,1)) + +container.sprites.Add(Sprite("network_good", set_networkicons, 0,0,1,1)) +container.sprites.Add(Sprite("network_bad", set_networkicons, 0,1,1,1)) + +container.sprites.Add(Sprite("level_a_on", set_levelicons, 0,0,1,1)) +container.sprites.Add(Sprite("level_a_a", set_levelicons, 0,1,1,1)) +container.sprites.Add(Sprite("level_a_b", set_levelicons, 0,2,1,1)) +container.sprites.Add(Sprite("level_b_on", set_levelicons, 1,0,1,1)) +container.sprites.Add(Sprite("level_b_a", set_levelicons, 1,1,1,1)) +container.sprites.Add(Sprite("level_b_b", set_levelicons, 1,2,1,1)) +container.sprites.Add(Sprite("level_c_on", set_levelicons, 2,0,1,1)) +container.sprites.Add(Sprite("level_c_a", set_levelicons, 2,1,1,1)) +container.sprites.Add(Sprite("level_c_b", set_levelicons, 2,2,1,1)) + +container.sprites.Add(Sprite("sidebar_refresh_a", set_sidebaricons, 0,0,1,1)) +container.sprites.Add(Sprite("sidebar_refresh_b", set_sidebaricons, 0,1,1,1)) +container.sprites.Add(Sprite("sidebar_friend_a", set_sidebaricons, 1,0,1,1)) +container.sprites.Add(Sprite("sidebar_friend_b", set_sidebaricons, 1,1,1,1)) +container.sprites.Add(Sprite("sidebar_filter_a", set_sidebaricons, 2,0,1,1)) +container.sprites.Add(Sprite("sidebar_filter_b", set_sidebaricons, 2,1,1,1)) +container.sprites.Add(Sprite("sidebar_info_a", set_sidebaricons, 3,0,1,1)) +container.sprites.Add(Sprite("sidebar_info_b", set_sidebaricons, 3,1,1,1)) + +container.sprites.Add(Sprite("browser_a", set_browsericon, 0,0,1,1)) +container.sprites.Add(Sprite("browser_b", set_browsericon, 0,1,1,1)) + +container.sprites.Add(Sprite("timerclock_a", set_timerclock, 0,0,1,1)) +container.sprites.Add(Sprite("timerclock_b", set_timerclock, 0,1,1,1)) + +anim = Animation("base") +anim.body.frames.Add(AnimKeyframe(0, 0, -4, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) +container.animations.Add(anim) + +anim = Animation("idle") +anim.back_foot.frames.Add(AnimKeyframe(0, -7, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0, 7, 0, 0)) +container.animations.Add(anim) + +anim = Animation("inair") +anim.back_foot.frames.Add(AnimKeyframe(0, -3, 0, -0.1)) +anim.front_foot.frames.Add(AnimKeyframe(0, 3, 0, -0.1)) +container.animations.Add(anim) + +anim = Animation("walk") +anim.body.frames.Add(AnimKeyframe(0.0, 0, 0, 0)) +anim.body.frames.Add(AnimKeyframe(0.2, 0,-1, 0)) +anim.body.frames.Add(AnimKeyframe(0.4, 0, 0, 0)) +anim.body.frames.Add(AnimKeyframe(0.6, 0, 0, 0)) +anim.body.frames.Add(AnimKeyframe(0.8, 0,-1, 0)) +anim.body.frames.Add(AnimKeyframe(1.0, 0, 0, 0)) + +anim.back_foot.frames.Add(AnimKeyframe(0.0, 8, 0, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0.2, -8, 0, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0.4,-10,-4, 0.2)) +anim.back_foot.frames.Add(AnimKeyframe(0.6, -8,-8, 0.3)) +anim.back_foot.frames.Add(AnimKeyframe(0.8, 4,-4,-0.2)) +anim.back_foot.frames.Add(AnimKeyframe(1.0, 8, 0, 0)) + +anim.front_foot.frames.Add(AnimKeyframe(0.0,-10,-4, 0.2)) +anim.front_foot.frames.Add(AnimKeyframe(0.2, -8,-8, 0.3)) +anim.front_foot.frames.Add(AnimKeyframe(0.4, 4,-4,-0.2)) +anim.front_foot.frames.Add(AnimKeyframe(0.6, 8, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0.8, 8, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(1.0,-10,-4, 0.2)) +container.animations.Add(anim) + +anim = Animation("hammer_swing") +anim.attach.frames.Add(AnimKeyframe(0.0, 0, 0, -0.10)) +anim.attach.frames.Add(AnimKeyframe(0.3, 0, 0, 0.25)) +anim.attach.frames.Add(AnimKeyframe(0.4, 0, 0, 0.30)) +anim.attach.frames.Add(AnimKeyframe(0.5, 0, 0, 0.25)) +anim.attach.frames.Add(AnimKeyframe(1.0, 0, 0, -0.10)) +container.animations.Add(anim) + +anim = Animation("ninja_swing") +anim.attach.frames.Add(AnimKeyframe(0.00, 0, 0, -0.25)) +anim.attach.frames.Add(AnimKeyframe(0.10, 0, 0, -0.05)) +anim.attach.frames.Add(AnimKeyframe(0.15, 0, 0, 0.35)) +anim.attach.frames.Add(AnimKeyframe(0.42, 0, 0, 0.40)) +anim.attach.frames.Add(AnimKeyframe(0.50, 0, 0, 0.35)) +anim.attach.frames.Add(AnimKeyframe(1.00, 0, 0, -0.25)) +container.animations.Add(anim) + +weapon = WeaponSpec(container, "hammer") +weapon.firedelay.Set(125) +weapon.damage.Set(3) +weapon.visual_size.Set(96) +weapon.offsetx.Set(4) +weapon.offsety.Set(-20) +container.weapons.hammer.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "gun") +weapon.firedelay.Set(125) +weapon.damage.Set(1) +weapon.ammoregentime.Set(500) +weapon.visual_size.Set(64) +weapon.offsetx.Set(32) +weapon.offsety.Set(0) +weapon.muzzleoffsetx.Set(50) +weapon.muzzleoffsety.Set(6) +container.weapons.gun.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "shotgun") +weapon.firedelay.Set(500) +weapon.damage.Set(1) +weapon.visual_size.Set(96) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +weapon.muzzleoffsetx.Set(70) +weapon.muzzleoffsety.Set(6) +container.weapons.shotgun.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "grenade") +weapon.firedelay.Set(500) # TODO: fix this +weapon.damage.Set(6) +weapon.visual_size.Set(96) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +container.weapons.grenade.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "laser") +weapon.firedelay.Set(800) +weapon.damage.Set(5) +weapon.visual_size.Set(92) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +container.weapons.laser.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "ninja") +weapon.firedelay.Set(800) +weapon.damage.Set(9) +weapon.visual_size.Set(96) +weapon.offsetx.Set(0) +weapon.offsety.Set(0) +weapon.muzzleoffsetx.Set(40) +weapon.muzzleoffsety.Set(-4) +container.weapons.ninja.base.Set(weapon) +container.weapons.id.Add(weapon) diff --git a/datasrc/datatypes.py b/datasrc/datatypes.py new file mode 100644 index 000000000..da47ef40d --- /dev/null +++ b/datasrc/datatypes.py @@ -0,0 +1,401 @@ +import sys + +GlobalIdCounter = 0 +def GetID(): + global GlobalIdCounter + GlobalIdCounter += 1 + return GlobalIdCounter +def GetUID(): + return "x%d"%GetID() + +def FixCasing(Str): + NewStr = "" + NextUpperCase = True + for c in Str: + if NextUpperCase: + NextUpperCase = False + NewStr += c.upper() + else: + if c == "_": + NextUpperCase = True + else: + NewStr += c.lower() + return NewStr + +def FormatName(type, name): + if "*" in type: + return "m_p" + FixCasing(name) + if "[]" in type: + return "m_a" + FixCasing(name) + return "m_" + FixCasing(name) + +class BaseType: + def __init__(self, type_name): + self._type_name = type_name + self._target_name = "INVALID" + self._id = GetID() # this is used to remember what order the members have in structures etc + + def Identifyer(self): return "x"+str(self._id) + def TargetName(self): return self._target_name + def TypeName(self): return self._type_name + def ID(self): return self._id; + + def EmitDeclaration(self, name): + return ["%s %s;"%(self.TypeName(), FormatName(self.TypeName(), name))] + def EmitPreDefinition(self, target_name): + self._target_name = target_name + return [] + def EmitDefinition(self, name): + return [] + +class MemberType: + def __init__(self, name, var): + self.name = name + self.var = var + +class Struct(BaseType): + def __init__(self, type_name): + BaseType.__init__(self, type_name) + def Members(self): + def sorter(a): + return a.var.ID() + m = [] + for name in self.__dict__: + if name[0] == "_": + continue + m += [MemberType(name, self.__dict__[name])] + try: + m.sort(key = sorter) + except: + for v in m: + print(v.name, v.var) + sys.exit(-1) + return m + + def EmitTypeDeclaration(self, name): + lines = [] + lines += ["struct " + self.TypeName()] + lines += ["{"] + for member in self.Members(): + lines += ["\t"+l for l in member.var.EmitDeclaration(member.name)] + lines += ["};"] + return lines + + def EmitPreDefinition(self, target_name): + BaseType.EmitPreDefinition(self, target_name) + lines = [] + for member in self.Members(): + lines += member.var.EmitPreDefinition(target_name+"."+member.name) + return lines + def EmitDefinition(self, name): + lines = ["/* %s */ {" % self.TargetName()] + for member in self.Members(): + lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] + lines += ["}"] + return lines + +class Array(BaseType): + def __init__(self, type): + BaseType.__init__(self, type.TypeName()) + self.type = type + self.items = [] + def Add(self, instance): + if instance.TypeName() != self.type.TypeName(): + error("bah") + self.items += [instance] + def EmitDeclaration(self, name): + return ["int m_Num%s;"%(FixCasing(name)), + "%s *%s;"%(self.TypeName(), FormatName("[]", name))] + def EmitPreDefinition(self, target_name): + BaseType.EmitPreDefinition(self, target_name) + + lines = [] + i = 0 + for item in self.items: + lines += item.EmitPreDefinition("%s[%d]"%(self.Identifyer(), i)) + i += 1 + + if len(self.items): + lines += ["static %s %s[] = {"%(self.TypeName(), self.Identifyer())] + for item in self.items: + itemlines = item.EmitDefinition("") + lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","] + lines += ["};"] + else: + lines += ["static %s *%s = 0;"%(self.TypeName(), self.Identifyer())] + + return lines + def EmitDefinition(self, name): + return [str(len(self.items))+","+self.Identifyer()] + +# Basic Types + +class Int(BaseType): + def __init__(self, value): + BaseType.__init__(self, "int") + self.value = value + def Set(self, value): + self.value = value + def EmitDefinition(self, name): + return ["%d"%self.value] + #return ["%d /* %s */"%(self.value, self._target_name)] + +class Float(BaseType): + def __init__(self, value): + BaseType.__init__(self, "float") + self.value = value + def Set(self, value): + self.value = value + def EmitDefinition(self, name): + return ["%ff"%self.value] + #return ["%d /* %s */"%(self.value, self._target_name)] + +class String(BaseType): + def __init__(self, value): + BaseType.__init__(self, "const char*") + self.value = value + def Set(self, value): + self.value = value + def EmitDefinition(self, name): + return ['"'+self.value+'"'] + +class Pointer(BaseType): + def __init__(self, type, target): + BaseType.__init__(self, "%s*"%type().TypeName()) + self.target = target + def Set(self, target): + self.target = target + def EmitDefinition(self, name): + return ["&"+self.target.TargetName()] + +class TextureHandle(BaseType): + def __init__(self): + BaseType.__init__(self, "IGraphics::CTextureHandle") + def EmitDefinition(self, name): + return ["IGraphics::CTextureHandle()"] + +class SampleHandle(BaseType): + def __init__(self): + BaseType.__init__(self, "ISound::CSampleHandle") + def EmitDefinition(self, name): + return ["ISound::CSampleHandle()"] + +# helper functions + +def EmitTypeDeclaration(root): + for l in root().EmitTypeDeclaration(""): + print(l) + +def EmitDefinition(root, name): + for l in root.EmitPreDefinition(name): + print(l) + print("%s %s = " % (root.TypeName(), name)) + for l in root.EmitDefinition(name): + print(l) + print(";") + +# Network stuff after this + +class Object: + pass + +class Enum: + def __init__(self, name, values): + self.name = name + self.values = values + +class Flags: + def __init__(self, name, values): + self.name = name + self.values = values + +class NetObject: + def __init__(self, name, variables): + l = name.split(":") + self.name = l[0] + self.base = "" + if len(l) > 1: + self.base = l[1] + self.base_struct_name = "CNetObj_%s" % self.base + self.struct_name = "CNetObj_%s" % self.name + self.enum_name = "NETOBJTYPE_%s" % self.name.upper() + self.variables = variables + def emit_declaration(self): + if self.base: + lines = ["struct %s : public %s"%(self.struct_name,self.base_struct_name), "{"] + else: + lines = ["struct %s"%self.struct_name, "{"] + for v in self.variables: + lines += ["\t"+line for line in v.emit_declaration()] + lines += ["};"] + return lines + def emit_validate(self, base_item): + lines = ["case %s:" % self.enum_name] + lines += ["{"] + lines += ["\tconst %s *pObj = (const %s *)pData;"%(self.struct_name, self.struct_name)] + lines += ["\tif(sizeof(*pObj) != Size) return -1;"] + variables = self.variables + if base_item: + variables += base_item.variables + for v in variables: + lines += ["\t"+line for line in v.emit_validate()] + lines += ["\treturn 0;"] + lines += ["}"] + return lines + + +class NetEvent(NetObject): + def __init__(self, name, variables): + NetObject.__init__(self, name, variables) + self.base_struct_name = "CNetEvent_%s" % self.base + self.struct_name = "CNetEvent_%s" % self.name + self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() + +class NetMessage(NetObject): + def __init__(self, name, variables): + NetObject.__init__(self, name, variables) + self.base_struct_name = "CNetMsg_%s" % self.base + self.struct_name = "CNetMsg_%s" % self.name + self.enum_name = "NETMSGTYPE_%s" % self.name.upper() + def emit_unpack(self): + lines = [] + lines += ["case %s:" % self.enum_name] + lines += ["{"] + lines += ["\t%s *pMsg = (%s *)m_aMsgData;" % (self.struct_name, self.struct_name)] + lines += ["\t(void)pMsg;"] + for v in self.variables: + lines += ["\t"+line for line in v.emit_unpack()] + for v in self.variables: + lines += ["\t"+line for line in v.emit_unpack_check()] + lines += ["} break;"] + return lines + def emit_declaration(self): + extra = [] + extra += ["\tint MsgID() const { return %s; }" % self.enum_name] + extra += ["\t"] + extra += ["\tbool Pack(CMsgPacker *pPacker)"] + extra += ["\t{"] + #extra += ["\t\tmsg_pack_start(%s, flags);"%self.enum_name] + for v in self.variables: + extra += ["\t\t"+line for line in v.emit_pack()] + extra += ["\t\treturn pPacker->Error() != 0;"] + extra += ["\t}"] + + + lines = NetObject.emit_declaration(self) + lines = lines[:-1] + extra + lines[-1:] + return lines + + +class NetVariable: + def __init__(self, name, default=None): + self.name = name + self.default = None if default is None else str(default) + def emit_declaration(self): + return [] + def emit_validate(self): + return [] + def emit_pack(self): + return [] + def emit_unpack(self): + return [] + def emit_unpack_check(self): + return [] + +class NetString(NetVariable): + def emit_declaration(self): + return ["const char *%s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetString();" % self.name] + def emit_pack(self): + return ["pPacker->AddString(%s, -1);" % self.name] + +class NetStringStrict(NetVariable): + def emit_declaration(self): + return ["const char *%s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);" % self.name] + def emit_pack(self): + return ["pPacker->AddString(%s, -1);" % self.name] + +class NetIntAny(NetVariable): + def emit_declaration(self): + return ["int %s;"%self.name] + def emit_unpack(self): + if self.default is None: + return ["pMsg->%s = pUnpacker->GetInt();" % self.name] + else: + return ["pMsg->%s = pUnpacker->GetIntOrDefault(%s);" % (self.name, self.default)] + def emit_pack(self): + return ["pPacker->AddInt(%s);" % self.name] + +class NetIntRange(NetIntAny): + def __init__(self, name, min, max, default=None): + NetIntAny.__init__(self,name,default=default) + self.min = str(min) + self.max = str(max) + def emit_validate(self): + return ["if(!CheckInt(\"%s\", pObj->%s, %s, %s)) return -1;"%(self.name, self.name, self.min, self.max)] + def emit_unpack_check(self): + return ["if(!CheckInt(\"%s\", pMsg->%s, %s, %s)) break;"%(self.name, self.name, self.min, self.max)] + +class NetEnum(NetIntRange): + def __init__(self, name, enum): + NetIntRange.__init__(self, name, 0, len(enum.values)-1) + +class NetFlag(NetIntAny): + def __init__(self, name, flag): + NetIntAny.__init__(self, name) + if len(flag.values) > 0: + self.mask = "%s_%s" % (flag.name, flag.values[0]) + for i in flag.values[1:]: + self.mask += "|%s_%s" % (flag.name, i) + else: + self.mask = "0" + def emit_validate(self): + return ["if(!CheckFlag(\"%s\", pObj->%s, %s)) return -1;"%(self.name, self.name, self.mask)] + def emit_unpack_check(self): + return ["if(!CheckFlag(\"%s\", pMsg->%s, %s)) break;"%(self.name, self.name, self.mask)] + +class NetBool(NetIntRange): + def __init__(self, name, default=None): + default = None if default is None else int(default) + NetIntRange.__init__(self,name,0,1,default=default) + +class NetTick(NetIntRange): + def __init__(self, name): + NetIntRange.__init__(self,name,0,'max_int') + +class NetArray(NetVariable): + def __init__(self, var, size): + self.base_name = var.name + self.var = var + self.size = size + self.name = self.base_name + "[%d]"%self.size + def emit_declaration(self): + self.var.name = self.name + return self.var.emit_declaration() + def emit_validate(self): + lines = [] + for i in range(self.size): + self.var.name = self.base_name + "[%d]"%i + lines += self.var.emit_validate() + return lines + def emit_unpack(self): + lines = [] + for i in range(self.size): + self.var.name = self.base_name + "[%d]"%i + lines += self.var.emit_unpack() + return lines + def emit_pack(self): + lines = [] + for i in range(self.size): + self.var.name = self.base_name + "[%d]"%i + lines += self.var.emit_pack() + return lines + def emit_unpack_check(self): + lines = [] + for i in range(self.size): + self.var.name = self.base_name + "[%d]"%i + lines += self.var.emit_unpack_check() + return lines diff --git a/datasrc/maps b/datasrc/maps new file mode 160000 index 000000000..1d3401a37 --- /dev/null +++ b/datasrc/maps @@ -0,0 +1 @@ +Subproject commit 1d3401a37a3334e311faf18a22aeff0e0ac9ee65 diff --git a/datasrc/network.py b/datasrc/network.py new file mode 100644 index 000000000..20fa40287 --- /dev/null +++ b/datasrc/network.py @@ -0,0 +1,484 @@ +from datatypes import * + +Pickups = Enum("PICKUP", ["HEALTH", "ARMOR", "GRENADE", "SHOTGUN", "LASER", "NINJA", "GUN", "HAMMER"]) +Emotes = Enum("EMOTE", ["NORMAL", "PAIN", "HAPPY", "SURPRISE", "ANGRY", "BLINK"]) +Emoticons = Enum("EMOTICON", ["OOP", "EXCLAMATION", "HEARTS", "DROP", "DOTDOT", "MUSIC", "SORRY", "GHOST", "SUSHI", "SPLATTEE", "DEVILTEE", "ZOMG", "ZZZ", "WTF", "EYES", "QUESTION"]) +Votes = Enum("VOTE", ["UNKNOWN", "START_OP", "START_KICK", "START_SPEC", "END_ABORT", "END_PASS", "END_FAIL"]) # todo 0.8: add RUN_OP, RUN_KICK, RUN_SPEC; rem UNKNOWN +ChatModes = Enum("CHAT", ["NONE", "ALL", "TEAM", "WHISPER"]) + +PlayerFlags = Flags("PLAYERFLAG", ["ADMIN", "CHATTING", "SCOREBOARD", "READY", "DEAD", "WATCHING", "BOT"]) +GameFlags = Flags("GAMEFLAG", ["TEAMS", "FLAGS", "SURVIVAL", "RACE"]) +GameStateFlags = Flags("GAMESTATEFLAG", ["WARMUP", "SUDDENDEATH", "ROUNDOVER", "GAMEOVER", "PAUSED", "STARTCOUNTDOWN"]) +CoreEventFlags = Flags("COREEVENTFLAG", ["GROUND_JUMP", "AIR_JUMP", "HOOK_ATTACH_PLAYER", "HOOK_ATTACH_GROUND", "HOOK_HIT_NOHOOK"]) +RaceFlags = Flags("RACEFLAG", ["HIDE_KILLMSG", "FINISHMSG_AS_CHAT", "KEEP_WANTED_WEAPON"]) + +GameMsgIDs = Enum("GAMEMSG", ["TEAM_SWAP", "SPEC_INVALIDID", "TEAM_SHUFFLE", "TEAM_BALANCE", "CTF_DROP", "CTF_RETURN", + + "TEAM_ALL", "TEAM_BALANCE_VICTIM", "CTF_GRAB", + + "CTF_CAPTURE", + + "GAME_PAUSED"]) # todo 0.8: sort (1 para) + + +RawHeader = ''' + +#include + +enum +{ + INPUT_STATE_MASK=0x3f +}; + +enum +{ + TEAM_SPECTATORS=-1, + TEAM_RED, + TEAM_BLUE, + NUM_TEAMS, + + FLAG_MISSING=-3, + FLAG_ATSTAND, + FLAG_TAKEN, + + SPEC_FREEVIEW=0, + SPEC_PLAYER, + SPEC_FLAGRED, + SPEC_FLAGBLUE, + NUM_SPECMODES, + + SKINPART_BODY = 0, + SKINPART_MARKING, + SKINPART_DECORATION, + SKINPART_HANDS, + SKINPART_FEET, + SKINPART_EYES, + NUM_SKINPARTS, + + VOTE_CHOICE_NO = -1, + VOTE_CHOICE_PASS = 0, + VOTE_CHOICE_YES = 1 +}; +''' + +RawSource = ''' +#include +#include "protocol.h" +''' + +Enums = [ + Pickups, + Emotes, + Emoticons, + Votes, + ChatModes, + GameMsgIDs, +] + +Flags = [ + PlayerFlags, + GameFlags, + GameStateFlags, + CoreEventFlags, + RaceFlags, +] + +Objects = [ + + NetObject("PlayerInput", [ + NetIntRange("m_Direction", -1, 1), + NetIntAny("m_TargetX"), + NetIntAny("m_TargetY"), + + NetBool("m_Jump"), + NetIntAny("m_Fire"), + NetBool("m_Hook"), + + NetFlag("m_PlayerFlags", PlayerFlags), + + # 0 means "no wanted weapon", `1+weapon` means that `weapon` is wanted, + # and ninja is not a valid wanted weapon. + NetIntRange("m_WantedWeapon", 0, 'NUM_WEAPONS-1'), + NetIntAny("m_NextWeapon"), + NetIntAny("m_PrevWeapon"), + ]), + + NetObject("Projectile", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_VelX"), + NetIntAny("m_VelY"), + + NetIntRange("m_Type", 0, 'NUM_WEAPONS-1'), + NetTick("m_StartTick"), + ]), + + NetObject("Laser", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_FromX"), + NetIntAny("m_FromY"), + + NetTick("m_StartTick"), + ]), + + NetObject("Pickup", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + + NetEnum("m_Type", Pickups), + ]), + + NetObject("Flag", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + + NetIntRange("m_Team", 'TEAM_RED', 'TEAM_BLUE') + ]), + + NetObject("GameData", [ + NetTick("m_GameStartTick"), + NetFlag("m_GameStateFlags", GameStateFlags), + NetTick("m_GameStateEndTick"), + ]), + + NetObject("GameDataTeam", [ + NetIntAny("m_TeamscoreRed"), + NetIntAny("m_TeamscoreBlue"), + ]), + + NetObject("GameDataFlag", [ + NetIntRange("m_FlagCarrierRed", 'FLAG_MISSING', 'MAX_CLIENTS-1'), + NetIntRange("m_FlagCarrierBlue", 'FLAG_MISSING', 'MAX_CLIENTS-1'), + NetTick("m_FlagDropTickRed"), + NetTick("m_FlagDropTickBlue"), + ]), + + NetObject("CharacterCore", [ + NetTick("m_Tick"), + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_VelX"), + NetIntAny("m_VelY"), + + NetIntAny("m_Angle"), + NetIntRange("m_Direction", -1, 1), + + NetIntRange("m_Jumped", 0, 3), + NetIntRange("m_HookedPlayer", -1, 'MAX_CLIENTS-1'), + NetIntRange("m_HookState", -1, 5), + NetTick("m_HookTick"), + + NetIntAny("m_HookX"), + NetIntAny("m_HookY"), + NetIntAny("m_HookDx"), + NetIntAny("m_HookDy"), + ]), + + NetObject("Character:CharacterCore", [ + NetIntRange("m_Health", 0, 10), + NetIntRange("m_Armor", 0, 10), + NetIntAny("m_AmmoCount"), + NetIntRange("m_Weapon", -1, 'NUM_WEAPONS-1'), + NetEnum("m_Emote", Emotes), + NetTick("m_AttackTick"), + NetFlag("m_TriggeredEvents", CoreEventFlags), + ]), + + NetObject("PlayerInfo", [ + NetFlag("m_PlayerFlags", PlayerFlags), + NetIntAny("m_Score"), + NetIntAny("m_Latency"), + ]), + + NetObject("SpectatorInfo", [ + NetIntRange("m_SpecMode", 0, 'NUM_SPECMODES-1'), + NetIntRange("m_SpectatorID", -1, 'MAX_CLIENTS-1'), + NetIntAny("m_X"), + NetIntAny("m_Y"), + ]), + + ## Demo + + NetObject("De_ClientInfo", [ + NetBool("m_Local"), + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + + NetArray(NetIntAny("m_aName"), 4), + NetArray(NetIntAny("m_aClan"), 3), + + NetIntAny("m_Country"), + + NetArray(NetArray(NetIntAny("m_aaSkinPartNames"), 6), 6), + NetArray(NetBool("m_aUseCustomColors"), 6), + NetArray(NetIntAny("m_aSkinPartColors"), 6), + ]), + + NetObject("De_GameInfo", [ + NetFlag("m_GameFlags", GameFlags), + + NetIntRange("m_ScoreLimit", 0, 'max_int'), + NetIntRange("m_TimeLimit", 0, 'max_int'), + + NetIntRange("m_MatchNum", 0, 'max_int'), + NetIntRange("m_MatchCurrent", 0, 'max_int'), + ]), + + NetObject("De_TuneParams", [ + # todo: should be done differently + NetArray(NetIntAny("m_aTuneParams"), 32), + ]), + + ## Events + + NetEvent("Common", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + ]), + + + NetEvent("Explosion:Common", []), + NetEvent("Spawn:Common", []), + NetEvent("HammerHit:Common", []), + + NetEvent("Death:Common", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + ]), + + NetEvent("SoundWorld:Common", [ + NetIntRange("m_SoundID", 0, 'NUM_SOUNDS-1'), + ]), + + NetEvent("Damage:Common", [ # Unused yet + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetIntAny("m_Angle"), + NetIntRange("m_HealthAmount", 0, 9), + NetIntRange("m_ArmorAmount", 0, 9), + NetBool("m_Self"), + ]), + + ## Race + # todo 0.8: move up + NetObject("PlayerInfoRace", [ + NetTick("m_RaceStartTick"), + ]), + + NetObject("GameDataRace", [ + NetIntRange("m_BestTime", -1, 'max_int'), + NetIntRange("m_Precision", 0, 3), + NetFlag("m_RaceFlags", RaceFlags), + ]), +] + +Messages = [ + + ### Server messages + NetMessage("Sv_Motd", [ + NetString("m_pMessage"), + ]), + + NetMessage("Sv_Broadcast", [ + NetString("m_pMessage"), + ]), + + NetMessage("Sv_Chat", [ + NetIntRange("m_Mode", 0, 'NUM_CHATS-1'), + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetIntRange("m_TargetID", -1, 'MAX_CLIENTS-1'), + NetStringStrict("m_pMessage"), + ]), + + NetMessage("Sv_Team", [ + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + NetBool("m_Silent"), + NetTick("m_CooldownTick"), + ]), + + NetMessage("Sv_KillMsg", [ + NetIntRange("m_Killer", -2, 'MAX_CLIENTS-1'), + NetIntRange("m_Victim", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Weapon", -3, 'NUM_WEAPONS-1'), + NetIntAny("m_ModeSpecial"), + ]), + + NetMessage("Sv_TuneParams", []), + NetMessage("Sv_ExtraProjectile", []), + NetMessage("Sv_ReadyToEnter", []), + + NetMessage("Sv_WeaponPickup", [ + NetIntRange("m_Weapon", 0, 'NUM_WEAPONS-1'), + ]), + + NetMessage("Sv_Emoticon", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetEnum("m_Emoticon", Emoticons), + ]), + + NetMessage("Sv_VoteClearOptions", []), + + NetMessage("Sv_VoteOptionListAdd", []), + + NetMessage("Sv_VoteOptionAdd", [ + NetStringStrict("m_pDescription"), + ]), + + NetMessage("Sv_VoteOptionRemove", [ + NetStringStrict("m_pDescription"), + ]), + + NetMessage("Sv_VoteSet", [ + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetEnum("m_Type", Votes), + NetIntRange("m_Timeout", 0, 60), + NetStringStrict("m_pDescription"), + NetStringStrict("m_pReason"), + ]), + + NetMessage("Sv_VoteStatus", [ + NetIntRange("m_Yes", 0, 'MAX_CLIENTS'), + NetIntRange("m_No", 0, 'MAX_CLIENTS'), + NetIntRange("m_Pass", 0, 'MAX_CLIENTS'), + NetIntRange("m_Total", 0, 'MAX_CLIENTS'), + ]), + + NetMessage("Sv_ServerSettings", [ + NetBool("m_KickVote"), + NetIntRange("m_KickMin", 0, 'MAX_CLIENTS'), + NetBool("m_SpecVote"), + NetBool("m_TeamLock"), + NetBool("m_TeamBalance"), + NetIntRange("m_PlayerSlots", 0, 'MAX_CLIENTS'), + ]), + + NetMessage("Sv_ClientInfo", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetBool("m_Local"), + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + NetStringStrict("m_pName"), + NetStringStrict("m_pClan"), + NetIntAny("m_Country"), + NetArray(NetStringStrict("m_apSkinPartNames"), 6), + NetArray(NetBool("m_aUseCustomColors"), 6), + NetArray(NetIntAny("m_aSkinPartColors"), 6), + NetBool("m_Silent"), + ]), + + NetMessage("Sv_GameInfo", [ + NetFlag("m_GameFlags", GameFlags), + + NetIntRange("m_ScoreLimit", 0, 'max_int'), + NetIntRange("m_TimeLimit", 0, 'max_int'), + + NetIntRange("m_MatchNum", 0, 'max_int'), + NetIntRange("m_MatchCurrent", 0, 'max_int'), + ]), + + NetMessage("Sv_ClientDrop", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetStringStrict("m_pReason"), + NetBool("m_Silent"), + ]), + + NetMessage("Sv_GameMsg", []), + + ## Demo messages + NetMessage("De_ClientEnter", [ + NetStringStrict("m_pName"), + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + ]), + + NetMessage("De_ClientLeave", [ + NetStringStrict("m_pName"), + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetStringStrict("m_pReason"), + ]), + + ### Client messages + NetMessage("Cl_Say", [ + NetIntRange("m_Mode", 0, 'NUM_CHATS-1'), + NetIntRange("m_Target", -1, 'MAX_CLIENTS-1'), + NetStringStrict("m_pMessage"), + ]), + + NetMessage("Cl_SetTeam", [ + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + ]), + + NetMessage("Cl_SetSpectatorMode", [ + NetIntRange("m_SpecMode", 0, 'NUM_SPECMODES-1'), + NetIntRange("m_SpectatorID", -1, 'MAX_CLIENTS-1'), + ]), + + NetMessage("Cl_StartInfo", [ + NetStringStrict("m_pName"), + NetStringStrict("m_pClan"), + NetIntAny("m_Country"), + NetArray(NetStringStrict("m_apSkinPartNames"), 6), + NetArray(NetBool("m_aUseCustomColors"), 6), + NetArray(NetIntAny("m_aSkinPartColors"), 6), + ]), + + NetMessage("Cl_Kill", []), + + NetMessage("Cl_ReadyChange", []), + + NetMessage("Cl_Emoticon", [ + NetEnum("m_Emoticon", Emoticons), + ]), + + NetMessage("Cl_Vote", [ + NetIntRange("m_Vote", 'VOTE_CHOICE_NO', 'VOTE_CHOICE_YES'), + ]), + + NetMessage("Cl_CallVote", [ + NetStringStrict("m_Type"), + NetStringStrict("m_Value"), + NetStringStrict("m_Reason"), + NetBool("m_Force"), + ]), + + # todo 0.8: move up + NetMessage("Sv_SkinChange", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetArray(NetStringStrict("m_apSkinPartNames"), 6), + NetArray(NetBool("m_aUseCustomColors"), 6), + NetArray(NetIntAny("m_aSkinPartColors"), 6), + ]), + + NetMessage("Cl_SkinChange", [ + NetArray(NetStringStrict("m_apSkinPartNames"), 6), + NetArray(NetBool("m_aUseCustomColors"), 6), + NetArray(NetIntAny("m_aSkinPartColors"), 6), + ]), + + ## Race + NetMessage("Sv_RaceFinish", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Time", -1, 'max_int'), + NetIntAny("m_Diff"), + NetBool("m_RecordPersonal"), + NetBool("m_RecordServer", default=False), + ]), + + NetMessage("Sv_Checkpoint", [ + NetIntAny("m_Diff"), + ]), + + NetMessage("Sv_CommandInfo", [ + NetStringStrict("m_Name"), + NetStringStrict("m_ArgsFormat"), + NetStringStrict("m_HelpText") + ]), + + NetMessage("Sv_CommandInfoRemove", [ + NetStringStrict("m_Name") + ]), + + NetMessage("Cl_Command", [ + NetStringStrict("m_Name"), + NetStringStrict("m_Arguments") + ]), + +] diff --git a/license.txt b/license.txt new file mode 100644 index 000000000..f01cdcd3a --- /dev/null +++ b/license.txt @@ -0,0 +1,38 @@ +Copyright (C) 2007-2022 Magnus Auvinen + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +------------------------------------------------------------------------ + +All content under 'data' and 'datasrc' except the font (which has its own +license) is released under CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/). + +Authors: android272, Chi11y (chi1), Crises, Daniel, Echchouik, Fisico, + leovilok, Landil, Lappi, LordSk, maikka, matricks, Pocram, + red_com, serpis, SkizZ, somerunce, Sonix, Stephanator, teetow, + Ubu, Zatline + +------------------------------------------------------------------------ + +IMPORTANT NOTE! The source under src/engine/external are stripped +libraries with their own licenses. Mostly BSD or zlib/libpng license but +check the individual libraries. + +------------------------------------------------------------------------ + +With that being said, contact us if there is anything you want to do +that the license does not permit. diff --git a/other/config_directory.bat b/other/config_directory.bat new file mode 100644 index 000000000..96a9ec812 --- /dev/null +++ b/other/config_directory.bat @@ -0,0 +1 @@ +@start explorer %APPDATA%\Teeworlds diff --git a/other/icons/teeworlds.icns b/other/icons/teeworlds.icns new file mode 100644 index 000000000..22be3422e Binary files /dev/null and b/other/icons/teeworlds.icns differ diff --git a/other/icons/teeworlds.ico b/other/icons/teeworlds.ico new file mode 100644 index 000000000..3ddec5c3d Binary files /dev/null and b/other/icons/teeworlds.ico differ diff --git a/other/icons/teeworlds.rc b/other/icons/teeworlds.rc new file mode 100644 index 000000000..aa5dcb44f --- /dev/null +++ b/other/icons/teeworlds.rc @@ -0,0 +1 @@ +ID ICON "teeworlds.ico" diff --git a/other/icons/teeworlds_cl.rc b/other/icons/teeworlds_cl.rc new file mode 100644 index 000000000..a4eab1f95 --- /dev/null +++ b/other/icons/teeworlds_cl.rc @@ -0,0 +1 @@ +50h ICON "teeworlds.ico" diff --git a/other/icons/teeworlds_gcc.rc b/other/icons/teeworlds_gcc.rc new file mode 100644 index 000000000..aa5dcb44f --- /dev/null +++ b/other/icons/teeworlds_gcc.rc @@ -0,0 +1 @@ +ID ICON "teeworlds.ico" diff --git a/other/icons/teeworlds_srv.icns b/other/icons/teeworlds_srv.icns new file mode 100644 index 000000000..44a847ebb Binary files /dev/null and b/other/icons/teeworlds_srv.icns differ diff --git a/other/icons/teeworlds_srv.ico b/other/icons/teeworlds_srv.ico new file mode 100644 index 000000000..bde79f6a6 Binary files /dev/null and b/other/icons/teeworlds_srv.ico differ diff --git a/other/icons/teeworlds_srv.rc b/other/icons/teeworlds_srv.rc new file mode 100644 index 000000000..44287bb51 --- /dev/null +++ b/other/icons/teeworlds_srv.rc @@ -0,0 +1 @@ +ID ICON "teeworlds_srv.ico" diff --git a/other/icons/teeworlds_srv_cl.rc b/other/icons/teeworlds_srv_cl.rc new file mode 100644 index 000000000..8e18b64ce --- /dev/null +++ b/other/icons/teeworlds_srv_cl.rc @@ -0,0 +1 @@ +50h ICON "teeworlds_srv.ico" diff --git a/other/icons/teeworlds_srv_gcc.rc b/other/icons/teeworlds_srv_gcc.rc new file mode 100644 index 000000000..44287bb51 --- /dev/null +++ b/other/icons/teeworlds_srv_gcc.rc @@ -0,0 +1 @@ +ID ICON "teeworlds_srv.ico" diff --git a/readme.md b/readme.md new file mode 100644 index 000000000..367afa436 --- /dev/null +++ b/readme.md @@ -0,0 +1,214 @@ + + Packaging status + + +Teeworlds ![GitHub Actions](https://github.com/teeworlds/teeworlds/workflows/Build/badge.svg) +========= + +A retro multiplayer shooter +--------------------------- + +Teeworlds is a free online multiplayer game, available for all major +operating systems. Battle with up to 16 players in a variety of game +modes, including Team Deathmatch and Capture The Flag. You can even +design your own maps! + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. See license.txt for full license +text including copyright information. + +Please visit https://www.teeworlds.com/ for up-to-date information about +the game, including new versions, custom maps and much more. + +Originally written by Magnus Auvinen. + +--- + +Teeworlds supports two build systems: CMake and bam. + +Building on Linux or macOS (CMake) +========================== + +Installing dependencies +----------------------- + + # Debian/Ubuntu + sudo apt install build-essential cmake git libfreetype6-dev libsdl2-dev libpnglite-dev libwavpack-dev python3 + + # Fedora + sudo dnf install @development-tools cmake gcc-c++ git freetype-devel pnglite-devel python3 SDL2-devel wavpack-devel + + # Arch Linux (doesn't have pnglite in its repositories) + sudo pacman -S --needed base-devel cmake freetype2 git python sdl2 wavpack + + # macOS + brew install cmake freetype sdl2 + + +Downloading repository +---------------------- + + git clone https://github.com/teeworlds/teeworlds --recurse-submodules + cd teeworlds + + # If you already cloned the repository before, use: + # git submodule update --init + + +Building +-------- + + mkdir -p build + cd build + cmake .. + make + +On subsequent builds, you only have to repeat the `make` step. + +You can then run the client with `./teeworlds` and the server with +`./teeworlds_srv`. + + +Build options +------------- + +The following options can be passed to the `cmake ..` command line (between the +`cmake` and `..`) in the "Building" step above. + +`-GNinja`: Use the Ninja build system instead of Make. This automatically +parallelizes the build and is generally **faster**. (Needs `sudo apt install +ninja-build` on Debian, `sudo dnf install ninja-build` on Fedora, and `sudo +pacman -S --needed ninja` on Arch Linux.) + +`-DDEV=ON`: Enable debug mode and disable some release mechanics. This leads to +**faster** builds. + +`-DCLIENT=OFF`: Disable generation of the client target. Can be useful on +headless servers which don't have graphics libraries like SDL2 installed. + +Building on Linux or macOS (bam) +========================== + +Installing dependencies +----------------------- + + # Debian/Ubuntu 19.10+ + sudo apt install bam git libfreetype6-dev libsdl2-dev libpnglite-dev libwavpack-dev python3 + + # Fedora + sudo dnf install bam gcc-c++ git freetype-devel pnglite-devel python3 SDL2-devel wavpack-devel + + # Arch Linux (doesn't have pnglite in its repositories) + sudo pacman -S --needed base-devel bam freetype2 git python sdl2 wavpack + + # macOS + brew install bam freetype sdl2 + + # other (add bam to your path) + git clone https://github.com/teeworlds/bam + cd bam + ./make_unix.sh + + +Downloading repository +---------------------- + + git clone https://github.com/teeworlds/teeworlds --recurse-submodules + cd teeworlds + + # If you already cloned the repository before, use: + # git submodule update --init + + +Building +-------- + + bam + +The compiled game is located in a sub-folder of `build`. You can run the client from there with `./teeworlds` and the server with `./teeworlds_srv`. + + +Build options +------------- + +One of the following targets can be added to the `bam` command line: `game` (default), `server`, `client`, `content`, `masterserver`, `tools`. + +The following options can also be added. + +`conf=release` to build in release mode (defaults to `conf=debug`). + +`arch=x86` or `arch=x86_64` to force select an architecture. + +Building on Windows with Visual Studio & CMake +====================== + +Download and install some version of [Microsoft Visual +Studio](https://www.visualstudio.com/) (as of writing, MSVS Community 2019) +with the following components: + +* Desktop development with C++ (on the main page) +* Python development (on the main page) +* Git for Windows (in Individual Components → Code tools) + +Run Visual Studio. Open the Team Explorer (View → Team Explorer, Ctrl+^, +Ctrl+M). Click Clone (in the Team Explorer, Connect → Local Git Repositories). +Enter `https://github.com/teeworlds/teeworlds` into the first input box. Wait +for the download to complete (terminals might pop up). + +Wait until the CMake configuration is done (watch the Output windows at the +bottom). + +Select `teeworlds.exe` in the Select Startup Item… combobox next to the green +arrow. Wait for the compilation to finish. + +For subsequent builds you only have to click the button with the green arrow +again. + +Building on Windows with MSVC build tools & bam +====================== + +Download and install [Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and [Python](https://www.python.org/downloads/). + +Download and unzip [Teeworlds stable sources](https://github.com/teeworlds/teeworlds/releases) or [Teeworlds latest sources](https://github.com/teeworlds/teeworlds/archive/master.zip). + +Download and unzip [bam](https://github.com/matricks/bam/archive/v0.5.1.tar.gz) to `teeworlds-version\bam`. + +Run the `x64 Native Tools Command Prompt` (or `x86` for 32-bit) from the start menu. + + # Navigate to the Teeworlds source directory + cd ...\teeworlds-version + + # Build bam (use make_win32_msvc.bat for 32-bit) + cd bam + make_win64_msvc.bat + copy bam .. + cd .. + + # Build Teeworlds + bam conf=release + +Use `conf=debug` to build the debug version instead. You can also provide a target after the `bam` command : `game` (default), `server`, `client`, `content`, `masterserver`, `tools`. + +Building on Windows with MinGW & CMake +====================== + +Download and install MinGW with at least the following components: + +- mingw-developer-toolkit-bin +- mingw32-base-bin +- mingw32-gcc-g++-bin +- msys-base-bin + +Also install [Git](https://git-scm.com/downloads) (for downloading the source +code), [Python](https://www.python.org/downloads/) and +[CMake](https://cmake.org/download/). + +Open CMake ("CMake (cmake-gui)" in the start menu). Click "Browse Source" +(first line) and select the directory with the Teeworlds source code. Next, +click "Browse Build" and create a subdirectory for the build (e.g. called +"build"). Then click "Configure". Select "MinGW Makefiles" as the generator and +click "Finish". Wait a bit (until the progress bar is full). Then click +"Generate". + +You can now build Teeworlds by executing `mingw32-make` in the build directory. diff --git a/scripts/bash_completion.sh b/scripts/bash_completion.sh new file mode 100755 index 000000000..77155d3bc --- /dev/null +++ b/scripts/bash_completion.sh @@ -0,0 +1,114 @@ +#!/bin/bash + +function check_path() { + if [ "$1" == "file" ]; then if [ -f "$2" ]; then return; fi; fi + if [ "$1" == "directory" ]; then if [ -d "$2" ]; then return; fi; fi + + echo "Error: $1 $2 not found" + echo " make sure to call the script from the root of the teeworlds code" + exit 1 +} + +check_path file ./other/bash-completion/teeworlds_srv +check_path file ./other/bash-completion/teeworlds +check_path directory ./src/ + +function tw_configs() { + local flag + local line + for flag in "$@" + do + grep -r "MACRO_CONFIG_.*CFGFLAG_$flag" \ + src/ \ + --include={variables.h,config_variables.h} | + LC_ALL=C sort | while IFS= read -r line + do + line="$(echo "$line" | cut -d'(' -f2 | cut -d',' -f2)" + printf '%s ' "${line:1}" + done + done +} + +function tw_commands() { + local flag="$1" + local line + grep -roh "Register(\".*CFGFLAG_$flag" src/ | LC_ALL=C sort | while IFS= read -r line + do + line="$(echo "$line" | cut -d'(' -f2 | cut -d'"' -f2)" + printf '%s ' "$line" + done +} + +function tw_update_server() { + local cfgs + local cmds + local comp_helper + cfgs="$(tw_configs SERVER ECON)" + cfgs="\"${cfgs::-1}\"" + cmds="$(tw_commands SERVER)" + cmds="\"${cmds::-1}\"" + + read -r -d '' comp_helper <<-EOF + # generated start + # DO NOT EDIT THIS FUNCTION MANUALLY + # GENERATED BY ./scripts/bash_completion.sh + _teeworlds_srv_commands_helper() { + \tlocal cur=\"\$1\" + \tlocal configs=$cfgs + \tlocal commands=$cmds + \tCOMPREPLY+=(\$(compgen -W \"\$configs\" -- \"\$cur\")) + \tCOMPREPLY+=(\$(compgen -W \"\$commands\" -- \"\$cur\")) + } + # generated end + EOF + # prepare newlines for sed + comp_helper="$(echo "$comp_helper" | sed 's/$/\\n/' | tr -d '\n')" + # cut off last newline to not add empty lines every time the script is run + comp_helper="${comp_helper::-2}" + + sed -ie "/generated start/,/generated end/c\\$comp_helper" ./other/bash-completion/teeworlds_srv + + if [ -f /usr/share/bash-completion/completions/teeworlds_srv ] + then + cp ./other/bash-completion/teeworlds_srv /usr/share/bash-completion/completions/teeworlds_srv + fi +} + +function tw_update_client() { + local cfgs + local cmds + local comp_helper + cfgs="$(tw_configs CLIENT)" + cfgs="\"${cfgs::-1}\"" + cmds="$(tw_commands CLIENT)" + cmds="\"${cmds::-1}\"" + + read -r -d '' comp_helper <<-EOF + # generated start + # DO NOT EDIT THIS FUNCTION MANUALLY + # GENERATED BY ./scripts/bash_completion.sh + _teeworlds_commands_helper() { + \tlocal cur=\"\$1\" + \tlocal configs=$cfgs + \tlocal commands=$cmds + \tCOMPREPLY+=(\$(compgen -W \"\$configs\" -- \"\$cur\")) + \tCOMPREPLY+=(\$(compgen -W \"\$commands\" -- \"\$cur\")) + } + # generated end + EOF + # prepare newlines for sed + comp_helper="$(echo "$comp_helper" | sed 's/$/\\n/' | tr -d '\n')" + # cut off last newline to not add empty lines every time the script is run + comp_helper="${comp_helper::-2}" + + sed -ie "/generated start/,/generated end/c\\$comp_helper" ./other/bash-completion/teeworlds + + if [ -f /usr/share/bash-completion/completions/teeworlds ] + then + cp ./other/bash-completion/teeworlds /usr/share/bash-completion/completions/teeworlds + fi +} + +tw_update_server +tw_update_client + diff --git a/scripts/build.py b/scripts/build.py new file mode 100644 index 000000000..d9904c4a9 --- /dev/null +++ b/scripts/build.py @@ -0,0 +1,262 @@ +import imp, optparse, os, re, shutil, sys, zipfile +os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") +import twlib + +arguments = optparse.OptionParser() +arguments.add_option("-b", "--url-bam", default = "http://github.com/matricks/bam/archive/master.zip", help = "URL from which the bam source code will be downloaded") +arguments.add_option("-t", "--url-teeworlds", default = "http://github.com/teeworlds/teeworlds/archive/master.zip", help = "URL from which the teeworlds source code will be downloaded") +arguments.add_option("-r", "--release-type", default = "server_release client_release", help = "Parts of the game which should be builded (for example client_release, debug, server_release or a combination of any of them)") +(options, arguments) = arguments.parse_args() + +bam = options.url_bam[7:].split("/") +version_bam = re.search(r"\d\.\d\.\d", bam[len(bam)-1]) +if version_bam: + version_bam = version_bam.group(0) +else: + version_bam = "trunk" +teeworlds = options.url_teeworlds[7:].split("/") +version_teeworlds = re.search(r"\d\.\d\.\d", teeworlds[len(teeworlds)-1]) +if version_teeworlds: + version_teeworlds = version_teeworlds.group(0) +else: + version_teeworlds = "trunk" + +bam_execution_path = "" +if version_bam < "0.3.0": + bam_execution_path = "src%s" % os.sep + +name = "teeworlds" + +flag_clean = True +flag_download = True +flag_unpack = True +flag_build_bam = True +flag_build_teeworlds = True +flag_make_release = True + +if os.name == "nt": + platform = "win32" +else: + # get name + osname = os.popen("uname").readline().strip().lower() + if osname == "darwin": + osname = "osx" + + # get arch + machine = os.popen("uname -m").readline().strip().lower() + arch = "unknown" + + if machine[0] == "i" and machine[2:] == "86": + arch = "x86" + elif machine == "x86_64": + arch = "x86_64" + elif "power" in machine.lower(): + arch = "ppc" + + platform = osname + "_" + arch + +print("%s-%s-%s" % (name, version_teeworlds, platform)) + +root_dir = os.getcwd() + os.sep +work_dir = root_dir + "scripts/work" + +def unzip(filename, where): + try: + z = zipfile.ZipFile(filename, "r") + except: + return False + list = "\n" + for name in z.namelist(): + list += "%s\n" % name + try: os.makedirs(where+"/"+os.path.dirname(name)) + except: pass + + try: + f = open(where+"/"+name, "wb") + f.write(z.read(name)) + f.close() + except: pass + + z.close() + + directory = "[^/\n]*?/" + part_1 = "(?<=\n)" + part_2 = "[^/\n]+(?=\n)" + regular_expression = r"%s%s" % (part_1, part_2) + main_directory = re.search(regular_expression, list) + while main_directory == None: + part_1 += directory + regular_expression = r"%s%s" % (part_1, part_2) + main_directory = re.search(regular_expression, list) + main_directory = re.search(r".*/", "./%s" % main_directory.group(0)) + return main_directory.group(0) + +def bail(reason): + print(reason) + os.chdir(work_dir) + sys.exit(-1) + +def clean(): + print("*** cleaning ***") + try: shutil.rmtree(work_dir) + except: pass + +def file_exists(file): + try: + open(file).close() + return True + except: + return False; + +def search_object(directory, object): + directory = os.listdir(directory) + for entry in directory: + match = re.search(object, entry) + if match != None: + return entry + +# clean +if flag_clean: + clean() + +# make dir +try: os.mkdir(work_dir) +except: pass + +# change dir +os.chdir(work_dir) + +# download +if flag_download: + print("*** downloading bam source package ***") + src_package_bam = twlib.fetch_file(options.url_bam) + if src_package_bam: + if version_bam == 'trunk': + version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_bam) + if version: + version_bam = version.group(1) + else: + bail("couldn't find bam source package and couldn't download it") + + print("*** downloading %s source package ***" % name) + src_package_teeworlds = twlib.fetch_file(options.url_teeworlds) + if src_package_teeworlds: + if version_teeworlds == 'trunk': + version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_teeworlds) + if version: + version_teeworlds = version.group(1) + else: + bail("couldn't find %s source package and couldn't download it" % name) + +# unpack +if flag_unpack: + print("*** unpacking source ***") + if hasattr(locals(), 'src_package_bam') == False: + src_package_bam = search_object(work_dir, r"bam.*?\.") + if not src_package_bam: + bail("couldn't find bam source package") + src_dir_bam = unzip(src_package_bam, ".") + if not src_dir_bam: + bail("couldn't unpack bam source package") + + if hasattr(locals(), 'src_package_teeworlds') == False: + src_package_teeworlds = search_object(work_dir, r"teeworlds.*?\.") + if not src_package_bam: + bail("couldn't find %s source package" % name) + src_dir_teeworlds = unzip(src_package_teeworlds, ".") + if not src_dir_teeworlds: + bail("couldn't unpack %s source package" % name) + +# build bam +if flag_build_bam: + print("*** building bam ***") + os.chdir("%s/%s" % (work_dir, src_dir_bam)) + if os.name == "nt": + if os.system("g++ -v >nul 2>&1") == 0: + print("using gcc") + os.system("make_win32_mingw.bat") + else: + print("using cl") + os.system("make_win32_msvc.bat") + if file_exists("%sbam.exe" % bam_execution_path) == False: + bail("failed to build bam") + else: + os.system("sh make_unix.sh") + if file_exists("%sbam" % bam_execution_path) == False: + bail("failed to build bam") + os.chdir(work_dir) + +# build the game +if flag_build_teeworlds: + print("*** building %s ***" % name) + if hasattr(locals(), 'src_dir_bam') == False: + src_dir_bam = search_object(work_dir, r"bam[^\.]*$") + os.sep + if src_dir_bam: + directory = src_dir_bam + bam_execution_path + file = r"bam" + if os.name == "nt": + file += r"\.exe" + if not search_object(directory, file): + bail("couldn't find bam") + else: + bail("couldn't find bam") + if hasattr(locals(), 'src_dir_teeworlds') == False: + src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") + if not src_dir_teeworlds: + bail("couldn't find %s source" % name) + command = 1 + if os.name == "nt": + if os.system("g++ -v >nul 2>&1") == 0: + print("using gcc") + os.chdir(src_dir_teeworlds) + command = os.system('"%s\\%s%sbam" %s' % (work_dir, src_dir_bam, bam_execution_path, options.release_type)) + else: + print("using cl") + file = open("build.bat", "wb") + content = "@echo off\n" + content += "@REM check if we already have the tools in the environment\n" + content += "if exist \"%VCINSTALLDIR%\" (\ngoto compile\n)\n" + content += "@REM Check for Visual Studio\n" + content += "if exist \"%VS100COMNTOOLS%\" (\nset VSPATH=\"%VS100COMNTOOLS%\"\ngoto set_env\n)\n" + content += "if exist \"%VS90COMNTOOLS%\" (\nset VSPATH=\"%VS90COMNTOOLS%\"\ngoto set_env\n)\n" + content += "if exist \"%VS80COMNTOOLS%\" (\nset VSPATH=\"%VS80COMNTOOLS%\"\ngoto set_env\n)\n\n" + content += "echo You need Microsoft Visual Studio 8, 9 or 10 installed\n" + content += "exit\n" + content += "@ setup the environment\n" + content += ":set_env\n" + content += "call %VSPATH%vsvars32.bat\n\n" + content += ":compile\n" + content += 'cd %s\n"%s\\%s%sbam" config\n"%s\\%s%sbam" %s' % (src_dir_teeworlds, work_dir, src_dir_bam, bam_execution_path, work_dir, src_dir_bam, bam_execution_path, options.release_type) + file.write(content.encode()) + file.close() + command = os.system("build.bat") + else: + os.chdir(src_dir_teeworlds) + command = os.system("%s/%s%sbam %s" % (work_dir, src_dir_bam, bam_execution_path, options.release_type)) + if command != 0: + bail("failed to build %s" % name) + os.chdir(work_dir) + +# make release +if flag_make_release: + print("*** making release ***") + if hasattr(locals(), 'src_dir_teeworlds') == False: + src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") + if not src_dir_teeworlds: + bail("couldn't find %s source" % name) + os.chdir(src_dir_teeworlds) + command = '"%s/%s/scripts/make_release.py" %s %s' % (work_dir, src_dir_teeworlds, version_teeworlds, platform) + if os.name != "nt": + command = "python %s" % command + if os.system(command) != 0: + bail("failed to make a relase of %s" % name) + final_output = "FAIL" + for f in os.listdir("."): + if version_teeworlds in f and platform in f and name in f and (".zip" in f or ".tar.gz" in f): + final_output = f + os.chdir(work_dir) + shutil.copy("%s/%s" % (src_dir_teeworlds, final_output), "../"+final_output) + os.chdir(root_dir) + clean() + +print("*** all done ***") diff --git a/scripts/check_header_guards.py b/scripts/check_header_guards.py new file mode 100755 index 000000000..7c57f690f --- /dev/null +++ b/scripts/check_header_guards.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +import os +import sys + +os.chdir(os.path.dirname(__file__) + "/..") + +PATH = "src/" +EXCEPTIONS = [ +] + +def check_file(filename): + if filename in EXCEPTIONS: + return False + error = False + with open(filename) as file: + for line in file: + if line == "// This file can be included several times.\n": + break + if line[0] == "/" or line[0] == "*" or line[0] == "\r" or line[0] == "\n" or line[0] == "\t": + continue + if line.startswith("#ifndef"): + header_guard = "#ifndef " + ("_".join(filename.split(PATH)[1].split("/"))[:-2]).upper() + "_H" + if line[:-1] != header_guard: + error = True + print("Wrong header guard in {}".format(filename)) + else: + error = True + print("Missing header guard in {}".format(filename)) + break + return error + +def check_dir(directory): + errors = 0 + file_list = os.listdir(directory) + for file in file_list: + path = directory + file + if os.path.isdir(path): + if file not in ("external", "generated"): + errors += check_dir(path + "/") + elif file.endswith(".h") and file != "keynames.h": + errors += check_file(path) + return errors + +if __name__ == '__main__': + sys.exit(int(check_dir(PATH) != 0)) diff --git a/scripts/cmd5.py b/scripts/cmd5.py new file mode 100644 index 000000000..07ee484b1 --- /dev/null +++ b/scripts/cmd5.py @@ -0,0 +1,35 @@ +import hashlib, sys, re + +alphanum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".encode() + +def cstrip(lines): + d = "".encode() + for l in lines: + l = re.sub("#.*".encode(), "".encode(), l) + l = re.sub("//.*".encode(), "".encode(), l) + d += l + " ".encode() + d = re.sub("\/\*.*?\*/".encode(), "".encode(), d) # remove /* */ comments + d = d.replace("\t".encode(), " ".encode()) # tab to space + d = re.sub(" *".encode(), " ".encode(), d) # remove double spaces + d = re.sub("".encode(), "".encode(), d) # remove /* */ comments + + d = d.strip() + + # this eats up cases like 'n {' + i = 1 + while i < len(d)-2: + if d[i:i + 1] == " ".encode(): + if not (d[i - 1:i] in alphanum and d[i+1:i + 2] in alphanum): + d = d[:i] + d[i + 1:] + i += 1 + return d + +f = "".encode() +for filename in sys.argv[1:]: + f += cstrip([l.strip() for l in open(filename, "rb")]) + +hash = hashlib.md5(f).hexdigest().lower()[16:] +#TODO 0.8: improve nethash creation +if hash == "cb14bf6dc197d153": + hash = "802f1be60a05665f" +print('#define GAME_NETVERSION_HASH "%s"' % hash) diff --git a/scripts/convert_l10n.py b/scripts/convert_l10n.py new file mode 100644 index 000000000..aab8c8fdd --- /dev/null +++ b/scripts/convert_l10n.py @@ -0,0 +1,131 @@ +import json +import polib +import os +import re +import time +import sys + +from collections import defaultdict + +os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") + +format = "{0:40} {1:8} {2:8} {3:8}".format +SOURCE_EXTS = [".c", ".cpp", ".h"] + +JSON_KEY_AUTHORS="authors" +JSON_KEY_TRANSL="translated strings" +JSON_KEY_UNTRANSL="needs translation" +JSON_KEY_OLDTRANSL="old translations" +JSON_KEY_CTXT="context" +JSON_KEY_OR="or" +JSON_KEY_TR="tr" + +SOURCE_LOCALIZE_RE=re.compile(br'Localize\("(?P([^"\\]|\\.)*)"(, ?"(?P([^"\\]|\\.)*)")?\)') + +def parse_source(): + l10n = defaultdict(lambda: []) + + def process_line(line, filename, lineno): + for match in SOURCE_LOCALIZE_RE.finditer(line): + str_ = match.group('str').decode() + ctxt = match.group('ctxt') + if ctxt is not None: + ctxt = ctxt.decode() + l10n[(str_, ctxt)].append((filename, lineno)) + + for root, dirs, files in os.walk("src"): + for name in files: + filename = os.path.join(root, name) + + if os.sep + "external" + os.sep in filename: + continue + + if os.path.splitext(filename)[1] in SOURCE_EXTS: + # HACK: Open source as binary file. + # Necessary some of teeworlds source files + # aren't utf-8 yet for some reason + for lineno, line in enumerate(open(filename, 'rb')): + # let lineno start with 1 + lineno += 1 + # process line + process_line(line, filename, lineno) + + return l10n + +def load_languagefile(filename): + return json.load(open(filename), strict=False) # accept \t tabs + +def write_languagefile(outputfilename, l10n_src, old_l10n_data): + outputfilename += '.po' + + po = polib.POFile() + po.metadata = { + 'Project-Id-Version': 'teeworlds-0.7_dev', + 'Report-Msgid-Bugs-To': 'translation@teeworlds.com', + 'POT-Creation-Date': time.strftime("%Y-%m-%d %H:%M%z"), + 'PO-Revision-Date': time.strftime("%Y-%m-%d %H:%M%z"), + 'Language-Team': 'Teeworlds Translations ', + 'MIME-Version': '1.0', + 'Content-Type': 'text/plain; charset=utf-8', + 'Content-Transfer-Encoding': '8bit', + } + + translations = {} + for type_ in ( + JSON_KEY_OLDTRANSL, + JSON_KEY_UNTRANSL, + JSON_KEY_TRANSL, + ): + if type_ not in old_l10n_data: + continue + translations.update({ + (t[JSON_KEY_OR], t.get(JSON_KEY_CTXT)): t[JSON_KEY_TR] + for t in old_l10n_data[type_] + if t[JSON_KEY_TR] + }) + + all_items = set(translations) | set(l10n_src) + tsl_items = set(translations) & set(l10n_src) + old_items = set(translations) - set(l10n_src) + new_items = set(l10n_src) - set(translations) + + for msg, ctxt in all_items: + po.append(polib.POEntry( + msgid=msg, + msgctxt=ctxt, + msgstr=translations.get((msg, ctxt), ""), + obsolete=(msg in old_items), + occurrences=l10n_src[msg], + )) + po.save(outputfilename) + +if __name__ == '__main__': + l10n_src = parse_source() + + po = polib.POFile() + po.metadata = { + 'Project-Id-Version': 'teeworlds-0.7_dev', + 'Report-Msgid-Bugs-To': 'translation@teeworlds.com', + 'POT-Creation-Date': time.strftime("%Y-%m-%d %H:%M%z"), + 'PO-Revision-Date': 'YEAR-MO-DA HO:MI+ZONE', + 'Language-Team': 'Teeworlds Translations ', + 'MIME-Version': '1.0', + 'Content-Type': 'text/plain; charset=utf-8', + 'Content-Transfer-Encoding': '8bit', + } + for (msg, ctxt), occurrences in l10n_src.items(): + commenttxt = ctxt + if(commenttxt): + commenttxt = 'Context: '+commenttxt + po.append(polib.POEntry(msgid=msg, msgstr="", occurrences=occurrences, msgctxt=ctxt, comment=commenttxt)) + po.save('datasrc/languages/base.pot') + + for filename in os.listdir("datasrc/languages"): + try: + if (os.path.splitext(filename)[1] == ".json" + and filename != "index.json"): + filename = "datasrc/languages/" + filename + write_languagefile(filename, l10n_src, load_languagefile(filename)) + except Exception as e: + print("Failed on {0}, re-raising for traceback".format(filename)) + raise diff --git a/scripts/copyright.py b/scripts/copyright.py new file mode 100755 index 000000000..c5221a50a --- /dev/null +++ b/scripts/copyright.py @@ -0,0 +1,63 @@ +import os, sys +os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") + +notice = [("/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */" + os.linesep).encode('utf-8'), ("/* If you are missing that file, acquire a complete release at teeworlds.com. */" + os.linesep).encode('utf-8')] +exclude = ["src%sengine%sexternal" % (os.sep, os.sep), "src%sosxlaunch" % os.sep, "src%sbase%shash_libtomcrypt.c" % (os.sep, os.sep)] +updated_files = 0 + +def fix_copyright_notice(filename): + global updated_files + f = open(filename, "rb") + lines = f.readlines() + f.close() + + i = 0 + length_lines = len(lines) + if length_lines > 0: + while i <= length_lines and (lines[i].decode("utf-8").lstrip()[:2] == "//" or lines[i].decode("utf-8").lstrip()[:2] == "/*" and lines[i].decode("utf-8").rstrip()[-2:] == "*/") and ("Magnus" in lines[i].decode("utf-8") or "magnus" in lines[i].decode("utf-8") or "Auvinen" in lines[i].decode("utf-8") or "auvinen" in lines[i].decode("utf-8") or "license" in lines[i].decode("utf-8") or "teeworlds" in lines[i].decode("utf-8")): + i += 1 + length_notice = len(notice) + if i > 0: + j = 0 + while lines[j] == notice[j]: + j += 1 + if j == length_notice: + return + k = j + j = 0 + while j < length_notice -1 - k: + lines = [notice[j]] + lines + j += 1 + while j < length_notice: + lines[j] = notice[j] + j += 1 + if length_lines == 0 or i == 0: + j = length_notice - 1 + while j >= 0: + lines = [notice[j]] + lines + j -= 1 + open(filename, "wb").writelines(lines) + updated_files += 1 + +skip = False +for root, dirs, files in os.walk("src"): + for excluding in exclude: + if root[:len(excluding)] == excluding: + skip = True + break + if skip == True: + skip = False + continue + for name in files: + filename = os.path.join(root, name) + if filename in exclude: + continue + if filename[-2:] != ".c" and filename[-4:] != ".cpp" and filename[-2:] != ".h": + continue + + fix_copyright_notice(filename) + +output = "file" +if updated_files != 1: + output += "s" +print("*** updated %d %s ***" % (updated_files, output)) diff --git a/scripts/darwin_change_dylib.py b/scripts/darwin_change_dylib.py new file mode 100644 index 000000000..6f3922572 --- /dev/null +++ b/scripts/darwin_change_dylib.py @@ -0,0 +1,63 @@ +from collections import namedtuple +import os +import re +import shlex +import subprocess + +Config = namedtuple('Config', 'install_name_tool otool verbose') + +def dylib_regex(name): + return re.compile(r'\S*{}\S*'.format(re.escape(name))) + +class ChangeDylib: + def __init__(self, config): + self.config = config + def _check_call(self, process_args, *args, **kwargs): + if self.config.verbose >= 1: + print("EXECUTING {}".format(" ".join(shlex.quote(x) for x in process_args))) + if not (self.config.verbose >= 2 and "stdout" not in kwargs): + kwargs["stdout"] = open(os.devnull, 'wb') + return subprocess.check_call(process_args, *args, **kwargs) + def _check_output(self, process_args, *args, **kwargs): + if self.config.verbose >= 1: + print("EXECUTING {} FOR OUTPUT".format(" ".join(shlex.quote(x) for x in process_args))) + return subprocess.check_output(process_args, *args, **kwargs) + def _install_name_tool(self, *args): + return self._check_call((self.config.install_name_tool,) + args) + def _otool(self, *args): + return self._check_output((self.config.otool,) + args) + + def change(self, filename, from_, to): + lines = self._otool("-L", filename).decode().splitlines() + regex = dylib_regex(from_) + matches = sum([regex.findall(l) for l in lines], []) + if len(matches) != 1: + if matches: + raise ValueError("More than one match found for {}: {}".format(from_, matches)) + else: + raise ValueError("No matches found for {}".format(from_)) + actual_from = matches[0] + self._install_name_tool("-change", actual_from, to, filename) + +def main(): + import argparse + p = argparse.ArgumentParser(description="Manipulate shared library dependencies for macOS") + + subcommands = p.add_subparsers(help="Subcommand", dest='command', metavar="COMMAND") + subcommands.required = True + + change = subcommands.add_parser("change", help="Change a shared library dependency to a given value") + change.add_argument('-v', '--verbose', action='count', help="Verbose output") + change.add_argument('--tools', nargs=2, help="Paths to the install_name_tool and otool", default=("install_name_tool", "otool")) + change.add_argument('filename', metavar="FILE", help="Filename of the executable to manipulate") + change.add_argument('from_', metavar="FROM", help="Fuzzily matched library name to change") + change.add_argument('to', metavar="TO", help="Exact name that the library dependency should be changed to") + args = p.parse_args() + + verbose = args.verbose or 0 + install_name_tool, otool = args.tools + dylib = ChangeDylib(Config(install_name_tool, otool, verbose)) + dylib.change(filename=args.filename, from_=args.from_, to=args.to) + +if __name__ == '__main__': + main() diff --git a/scripts/dmg.py b/scripts/dmg.py new file mode 100644 index 000000000..bf0335cda --- /dev/null +++ b/scripts/dmg.py @@ -0,0 +1,118 @@ +from collections import namedtuple +import os +import shlex +import subprocess +import tempfile +import time + +ConfigDmgtools = namedtuple('Config', 'dmg hfsplus newfs_hfs verbose') +ConfigHdiutil = namedtuple('Config', 'hdiutil verbose') + +def chunks(l, n): + """ + Yield successive n-sized chunks from l. + + From https://stackoverflow.com/a/312464. + """ + for i in range(0, len(l), n): + yield l[i:i + n] + +class Dmg: + def __init__(self, config): + self.config = config + + def _check_call(self, process_args, *args, **kwargs): + if self.config.verbose >= 1: + print("EXECUTING {}".format(" ".join(shlex.quote(x) for x in process_args))) + if not (self.config.verbose >= 2 and "stdout" not in kwargs): + kwargs["stdout"] = open(os.devnull, 'wb') + subprocess.check_call(process_args, *args, **kwargs) + +class Dmgtools(Dmg): + def _mkfs_hfs(self, *args): + self._check_call((self.config.newfs_hfs,) + args) + def _hfs(self, *args): + self._check_call((self.config.hfsplus,) + args) + def _dmg(self, *args): + self._check_call((self.config.dmg,) + args) + + def _create_hfs(self, hfs, volume_name, size): + if self.config.verbose >= 1: + print("TRUNCATING {} to {} bytes".format(hfs, size)) + with open(hfs, 'wb') as f: + f.truncate(size) + self._mkfs_hfs('-v', volume_name, hfs) + + def _symlink(self, hfs, target, link_name): + self._hfs(hfs, 'symlink', link_name, target) + + def _add(self, hfs, directory): + self._hfs(hfs, 'addall', directory) + + def _finish(self, hfs, dmg): + self._dmg('build', hfs, dmg) + + def create(self, dmg, volume_name, directory, symlinks): + input_size = sum(os.stat(os.path.join(path, f)).st_size for path, dirs, files in os.walk(directory) for f in files) + output_size = max(input_size * 2, 1024**2) + hfs = tempfile.mktemp(prefix=dmg + '.', suffix='.hfs') + self._create_hfs(hfs, volume_name, output_size) + self._add(hfs, directory) + for target, link_name in symlinks: + self._symlink(hfs, target, link_name) + self._finish(hfs, dmg) + if self.config.verbose >= 1: + print("REMOVING {}".format(hfs)) + os.remove(hfs) + +class Hdiutil(Dmg): + def _hdiutil(self, *args): + self._check_call((self.config.hdiutil,) + args) + + def create(self, dmg, volume_name, directory, symlinks): + if symlinks: + raise NotImplementedError("symlinks are not yet implemented") + for i in range(5): + if os.path.exists(volume_name + '.dmg'): + os.remove(volume_name + '.dmg') + try: + self._hdiutil('create', '-volname', volume_name, '-srcdir', directory, dmg) + except subprocess.CalledProcessError as e: + if i == 4: + raise e + print("Retrying hdiutil create") + time.sleep(5) + else: + break + +def main(): + import argparse + p = argparse.ArgumentParser(description="Manipulate dmg archives") + + subcommands = p.add_subparsers(help="Subcommand", dest='command', metavar="COMMAND") + subcommands.required = True + + create = subcommands.add_parser("create", help="Create a dmg archive from files or directories") + create.add_argument('-v', '--verbose', action='count', help="Verbose output") + createx = create.add_mutually_exclusive_group(required=True) + createx.add_argument('--dmgtools', nargs=3, help="Paths to the dmg and hfsplus executable (https://github.com/mozilla/libdmg-hfsplus) and the newfs_hfs executable (http://pkgs.fedoraproject.org/repo/pkgs/hfsplus-tools/diskdev_cmds-540.1.linux3.tar.gz/0435afc389b919027b69616ad1b05709/diskdev_cmds-540.1.linux3.tar.gz)") + createx.add_argument('--hdiutil', help="Path to the hdiutil (only exists for macOS at time of writing)") + create.add_argument('output', metavar="OUTPUT", help="Filename of the output dmg archive") + create.add_argument('volume_name', metavar="VOLUME_NAME", help="Name of the dmg archive") + create.add_argument('directory', metavar="DIR", help="Directory to create the archive from") + create.add_argument('--symlink', metavar="SYMLINK", nargs=2, action="append", help="Symlink the first argument under the second name") + args = p.parse_args() + + verbose = args.verbose or 0 + symlinks = args.symlink or [] + if args.dmgtools: + dmg, hfsplus, newfs_hfs = args.dmgtools + dmg = Dmgtools(ConfigDmgtools(dmg=dmg, hfsplus=hfsplus, newfs_hfs=newfs_hfs, verbose=verbose)) + elif args.hdiutil: + dmg = Hdiutil(ConfigHdiutil(hdiutil=args.hdiutil, verbose=verbose)) + else: + raise RuntimeError("unreachable") + dmg.create(volume_name=args.volume_name, directory=args.directory, dmg=args.output, symlinks=symlinks) + +if __name__ == '__main__': + main() diff --git a/scripts/download.py b/scripts/download.py new file mode 100644 index 000000000..81cf7ede3 --- /dev/null +++ b/scripts/download.py @@ -0,0 +1,53 @@ +import shutil, os, re, sys, zipfile +from distutils.dir_util import copy_tree +os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") +import twlib + +def unzip(filename, where): + try: + z = zipfile.ZipFile(filename, "r") + except: + return False + + # extract files + for name in z.namelist(): + z.extract(name, where) + z.close() + return z.namelist()[0] + +def downloadAll(targets): + version = "6c4af62b8c9853bfca1166d672a16abdbf9f0d26" + url = "https://github.com/teeworlds/teeworlds-libs/archive/{}.zip".format(version) + + # download and unzip + src_package_libs = twlib.fetch_file(url) + if not src_package_libs: + print("couldn't download libs") + sys.exit(-1) + libs_dir = unzip(src_package_libs, ".") + if not libs_dir: + print("couldn't unzip libs") + sys.exit(-1) + libs_dir = "teeworlds-libs-{}".format(version) + + if "sdl" in targets: + copy_tree(libs_dir + "/sdl/", "other/sdl/") + if "freetype" in targets: + copy_tree(libs_dir + "/freetype/", "other/freetype/") + + # cleanup + try: + shutil.rmtree(libs_dir) + os.remove(src_package_libs) + except: pass + +def main(): + import argparse + p = argparse.ArgumentParser(description="Download freetype and SDL library and header files for Windows.") + p.add_argument("targets", metavar="TARGET", nargs='+', choices=["sdl", "freetype"], help='Target to download. Valid choices are "sdl" and "freetype"') + args = p.parse_args() + + downloadAll(args.targets) + +if __name__ == '__main__': + main() diff --git a/scripts/git_revision.py b/scripts/git_revision.py new file mode 100644 index 000000000..ae1186c42 --- /dev/null +++ b/scripts/git_revision.py @@ -0,0 +1,21 @@ +import errno +import subprocess +try: + from subprocess import DEVNULL +except ImportError: + import os + DEVNULL = open(os.devnull, 'wb') +try: + FileNotFoundError +except NameError: + FileNotFoundError = OSError +try: + git_hash = subprocess.check_output(["git", "rev-parse", "--short=16", "HEAD"], stderr=DEVNULL).decode().strip() + definition = '"{}"'.format(git_hash) +except FileNotFoundError as e: + if e.errno != errno.ENOENT: + raise + definition = "0" +except subprocess.CalledProcessError: + definition = "0"; +print("const char *GIT_SHORTREV_HASH = {};".format(definition)) diff --git a/scripts/make_release.py b/scripts/make_release.py new file mode 100644 index 000000000..23a13ad84 --- /dev/null +++ b/scripts/make_release.py @@ -0,0 +1,279 @@ +import shutil, optparse, os, re, sys, zipfile +from distutils.dir_util import copy_tree +os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") +import twlib + +arguments = optparse.OptionParser(usage="usage: %prog VERSION PLATFORM [options]\n\nVERSION - Version number\nPLATFORM - Target platform (f.e. linux_x86, linux_x86_64, osx, src, win32, win64)") +arguments.add_option("-l", "--url-languages", default = "http://github.com/teeworlds/teeworlds-translation/archive/master.zip", help = "URL from which the teeworlds language files will be downloaded") +arguments.add_option("-m", "--url-maps", default = "http://github.com/teeworlds/teeworlds-maps/archive/master.zip", help = "URL from which the teeworlds maps files will be downloaded") +arguments.add_option("-s", "--source-dir", help = "Source directory which is used for building the package") +(options, arguments) = arguments.parse_args() +if len(sys.argv) != 3: + print("wrong number of arguments") + print(sys.argv[0], "VERSION PLATFORM") + sys.exit(-1) +if options.source_dir != None: + if os.path.exists(options.source_dir) == False: + print("Source directory " + options.source_dir + " doesn't exist") + exit(1) + os.chdir(options.source_dir) + +valid_platforms = ["win32", "win64", "osx", "linux_x86", "linux_x86_64", "src"] + +name = "teeworlds" +version = sys.argv[1] +platform = sys.argv[2] +exe_ext = "" +use_zip = 0 +use_gz = 1 +use_dmg = 0 +use_bundle = 0 +include_data = True +include_exe = True +include_src = False + +if not platform in valid_platforms: + print("not a valid platform") + print(valid_platforms) + sys.exit(-1) + +if platform == "src": + include_exe = False + include_src = True + use_zip = 1 +elif platform == 'win32' or platform == 'win64': + exe_ext = ".exe" + use_zip = 1 + use_gz = 0 +elif platform == 'osx': + use_dmg = 1 + use_gz = 0 + use_bundle = 1 + +def unzip(filename, where): + try: + z = zipfile.ZipFile(filename, "r") + except: + return False + for name in z.namelist(): + z.extract(name, where) + z.close() + return z.namelist()[0] + +def copydir(src, dst, excl=[]): + for root, dirs, files in os.walk(src, topdown=True): + if "/." in root or "\\." in root: + continue + for name in dirs: + if name[0] != '.': + os.mkdir(os.path.join(dst, root, name)) + for name in files: + if name[0] != '.': + shutil.copy(os.path.join(root, name), os.path.join(dst, root, name)) + +def copyfiles(src, dst): + dir = os.listdir(src) + for files in dir: + shutil.copy(os.path.join(src, files), os.path.join(dst, files)) + +def clean(): + print("*** cleaning ***") + try: + shutil.rmtree(package_dir) + shutil.rmtree(languages_dir) + shutil.rmtree(maps_dir) + os.remove(src_package_languages) + os.remove(src_package_maps) + except: pass + +def shell(cmd): + if os.system(cmd) != 0: + clean() + print("Non zero exit code on: os.system(%s)" % cmd) + sys.exit(1) + +package = "%s-%s-%s" %(name, version, platform) +package_dir = package + +source_package_dir = "build/" +if platform == 'win32' or platform == 'linux_x86': + source_package_dir += "x86/release/" +else: + source_package_dir += "x86_64/release/" + +print("cleaning target") +shutil.rmtree(package_dir, True) +os.mkdir(package_dir) + +print("download and extract languages") +src_package_languages = twlib.fetch_file(options.url_languages) +if not src_package_languages: + print("couldn't download languages") + sys.exit(-1) +languages_dir = unzip(src_package_languages, ".") +if not languages_dir: + print("couldn't unzip languages") + sys.exit(-1) + +print("download and extract maps") +src_package_maps = twlib.fetch_file(options.url_maps) +if not src_package_maps: + print("couldn't download maps") + sys.exit(-1) +maps_dir = unzip(src_package_maps, ".") +if not maps_dir: + print("couldn't unzip maps") + sys.exit(-1) + +print("adding files") +shutil.copy("readme.md", package_dir) +shutil.copy("license.txt", package_dir) +shutil.copy("storage.cfg", package_dir) + +if include_data and not use_bundle: + copy_tree(source_package_dir+"data", package_dir+"/data") + copy_tree(languages_dir, package_dir+"/data/languages") + copy_tree(maps_dir, package_dir+"/data/maps") + if platform[:3] == "win": + shutil.copy("other/config_directory.bat", package_dir) + shutil.copy(source_package_dir+"SDL2.dll", package_dir) + shutil.copy(source_package_dir+"freetype.dll", package_dir) + +if include_exe and not use_bundle: + shutil.copy(source_package_dir+name+exe_ext, package_dir) + shutil.copy(source_package_dir+name+"_srv"+exe_ext, package_dir) + +if include_src: + for p in ["src", "scripts", "datasrc", "other", "objs"]: + os.mkdir(os.path.join(package_dir, p)) + copydir(p, package_dir) + shutil.copy("bam.lua", package_dir) + shutil.copy("configure.lua", package_dir) + +if use_bundle: + bins = [name, name+'_srv', 'serverlaunch'] + platforms = ('x86_64') + for bin in bins: + to_lipo = [] + for p in platforms: + fname = bin+'_'+p + if os.path.isfile(fname): + to_lipo.append(fname) + if to_lipo: + shell("lipo -create -output "+bin+" "+" ".join(to_lipo)) + + # create Teeworlds appfolder + clientbundle_content_dir = os.path.join(package_dir, "Teeworlds.app/Contents") + clientbundle_bin_dir = os.path.join(clientbundle_content_dir, "MacOS") + clientbundle_resource_dir = os.path.join(clientbundle_content_dir, "Resources") + clientbundle_framework_dir = os.path.join(clientbundle_content_dir, "Frameworks") + binary_path = clientbundle_bin_dir + "/" + name+exe_ext + freetypelib_path = clientbundle_framework_dir + "/libfreetype.6.dylib" + os.mkdir(os.path.join(package_dir, "Teeworlds.app")) + os.mkdir(clientbundle_content_dir) + os.mkdir(clientbundle_bin_dir) + os.mkdir(clientbundle_resource_dir) + os.mkdir(clientbundle_framework_dir) + copy_tree(source_package_dir+"data", clientbundle_resource_dir+"/data") + copy_tree(languages_dir, clientbundle_resource_dir+"/data/languages") + copy_tree(maps_dir, clientbundle_resource_dir+"/data/maps") + shutil.copy("other/icons/Teeworlds.icns", clientbundle_resource_dir) + shutil.copy(source_package_dir+name+exe_ext, clientbundle_bin_dir) + shell("install_name_tool -change /usr/local/opt/freetype/lib/libfreetype.6.dylib @executable_path/../Frameworks/libfreetype.6.dylib " + binary_path) + shell("install_name_tool -change /usr/local/opt/sdl2/lib/libSDL2-2.0.0.dylib @executable_path/../Frameworks/libSDL2-2.0.0.dylib " + binary_path) + shell("cp /usr/local/opt/freetype/lib/libfreetype.6.dylib " + clientbundle_framework_dir) + shell("cp /usr/local/opt/libpng/lib/libpng16.16.dylib " + clientbundle_framework_dir) + shell("cp /usr/local/opt/sdl2/lib/libSDL2-2.0.0.dylib " + clientbundle_framework_dir) + shell("install_name_tool -change /usr/local/opt/libpng/lib/libpng16.16.dylib @executable_path/../Frameworks/libpng16.16.dylib " + freetypelib_path) + open(os.path.join(clientbundle_content_dir, "Info.plist"), "w").write(""" + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + teeworlds + CFBundleIconFile + Teeworlds + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + %s + CFBundleIdentifier + com.TeeworldsClient.app + NSHighResolutionCapable + + + + """ % (version)) + open(os.path.join(clientbundle_content_dir, "PkgInfo"), "w").write("APPL????") + + # create Teeworlds Server appfolder + serverbundle_content_dir = os.path.join(package_dir, "Teeworlds Server.app/Contents") + serverbundle_bin_dir = os.path.join(serverbundle_content_dir, "MacOS") + serverbundle_resource_dir = os.path.join(serverbundle_content_dir, "Resources") + os.mkdir(os.path.join(package_dir, "Teeworlds Server.app")) + os.mkdir(serverbundle_content_dir) + os.mkdir(serverbundle_bin_dir) + os.mkdir(serverbundle_resource_dir) + os.mkdir(os.path.join(serverbundle_resource_dir, "data")) + os.mkdir(os.path.join(serverbundle_resource_dir, "data/maps")) + os.mkdir(os.path.join(serverbundle_resource_dir, "data/mapres")) + copy_tree(maps_dir, serverbundle_resource_dir+"/data/maps") + shutil.copy("other/icons/Teeworlds_srv.icns", serverbundle_resource_dir) + shutil.copy(source_package_dir+name+"_srv"+exe_ext, serverbundle_bin_dir) + shutil.copy(source_package_dir+"serverlaunch"+exe_ext, serverbundle_bin_dir + "/"+name+"_server") + open(os.path.join(serverbundle_content_dir, "Info.plist"), "w").write(""" + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + teeworlds_server + CFBundleIconFile + Teeworlds_srv + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + %s + + + """ % (version)) + open(os.path.join(serverbundle_content_dir, "PkgInfo"), "w").write("APPL????") + +if use_zip: + print("making zip archive") + zf = zipfile.ZipFile("%s.zip" % package, 'w', zipfile.ZIP_DEFLATED) + + for root, dirs, files in os.walk(package_dir, topdown=True): + for name in files: + n = os.path.join(root, name) + zf.write(n, n) + #zf.printdir() + zf.close() + +if use_gz: + print("making tar.gz archive") + shell("tar czf %s.tar.gz %s" % (package, package_dir)) + +if use_dmg: + print("making disk image") + shell("rm -f %s.dmg %s_temp.dmg" % (package, package)) + shell("hdiutil create -srcfolder %s -volname Teeworlds -quiet %s_temp" % (package_dir, package)) + shell("hdiutil convert %s_temp.dmg -format UDBZ -o %s.dmg -quiet" % (package, package)) + shell("rm -f %s_temp.dmg" % package) + +clean() + +print("done") diff --git a/scripts/reconvert_l10n.py b/scripts/reconvert_l10n.py new file mode 100644 index 000000000..bb340ea0e --- /dev/null +++ b/scripts/reconvert_l10n.py @@ -0,0 +1,75 @@ +import polib +import json +import sys + +JSON_KEY_TRANSL="translated strings" +JSON_KEY_AUTHOR="authors" +JSON_KEY_MODIFY="modified by" +JSON_KEY_OR="or" +JSON_KEY_TR="tr" +JSON_KEY_CO="context" + +def reconvert(filename, json_filename): + """Converts a l10n file.po into a file.json, keeping author info from a previous file.json if possible""" + po = polib.pofile(open(filename, encoding='utf-8').read()) + translations = [] + + for entry in po: + if entry.msgstr: + t_entry = {} + t_entry[JSON_KEY_OR] = entry.msgid + t_entry[JSON_KEY_TR] = entry.msgstr + if entry.msgctxt is not None: + t_entry[JSON_KEY_CO] = entry.msgctxt + translations.append(t_entry) + + try: + previous_l10n = json.load(open(json_filename, encoding='utf-8'), strict=False) + + # remove tabs from data + authors = previous_l10n[JSON_KEY_AUTHOR] + for i, value in enumerate(authors[JSON_KEY_MODIFY]): + authors[JSON_KEY_MODIFY][i] = value.replace("\t", " ") + + result = {JSON_KEY_AUTHOR: authors, JSON_KEY_TRANSL: translations} + print(" extracted author info from " + json_filename) + + except IOError: + result = {JSON_KEY_AUTHOR: "", JSON_KEY_TRANSL: translations} + print(" failed to open " + json_filename + ", skipping author info") + + json.dump( + result, + open(json_filename, 'w', encoding='utf-8'), + ensure_ascii=False, + indent="\t", + separators=(',', ': '), + sort_keys=True, + ) + +def normalize(filename): + """Normalizes a l10n file.po for better version controlling""" + po = polib.pofile(open(filename).read()) + entries = list(sorted(sorted(po, key=lambda x: x.msgctxt or ""), key=lambda x: x.msgid)) + po.clear() + for entry in entries: + po.append(entry) + po.save(filename) + +def decrement_indent(filename): + """decrement indent level of file""" + with open(filename, encoding='utf-8') as f: + sanitized_json=f.read().replace('\n\t', '\n') + with open(filename, 'w', encoding='utf-8') as f: + f.write(sanitized_json) + +if __name__ == '__main__': + """Normalizes then converts a l10n file.po into a file.json, keeping author info from a previous file.json if possible""" + for filename in sys.argv[1:]: + assert(len(filename)>len(".po")) + json_filename = filename[:-3]+".json" + normalize(filename) + print(filename + " -> " + filename + " (normalized)") + reconvert(filename, json_filename) + decrement_indent(json_filename) + print(filename + " -> " + json_filename) diff --git a/scripts/refactor_count.py b/scripts/refactor_count.py new file mode 100644 index 000000000..dac42e2b8 --- /dev/null +++ b/scripts/refactor_count.py @@ -0,0 +1,351 @@ +import os, re, sys + +alphanum = "0123456789abcdefghijklmnopqrstuvwzyxABCDEFGHIJKLMNOPQRSTUVWXYZ_" +cpp_keywords = ["auto", "const", "double", "float", "int", "short", "struct", "unsigned", # C +"break", "continue", "else", "for", "long", "signed", "switch", "void", +"case", "default", "enum", "goto", "register", "sizeof", "typedef", "volatile", +"char", "do", "extern", "if", "return", "static", "union", "while", + +"asm", "dynamic_cast", "namespace", "reinterpret_cast", "try", # C++ +"bool", "explicit", "new", "static_cast", "typeid", +"catch", "false", "operator", "template", "typename", +"class", "friend", "private", "this", "using", +"const_cast", "inline", "public", "throw", "virtual", +"delete", "mutable", "protected", "true", "wchar_t"] + +allowed_words = [] + +#allowed_words += ["bitmap_left", "advance", "glyph"] # ft2 + + +allowed_words += ["qsort"] # stdio / stdlib +allowed_words += ["size_t", "cosf", "sinf", "asinf", "acosf", "atanf", "powf", "fabs", "rand", "powf", "fmod", "sqrtf"] # math.h +allowed_words += ["time_t", "time", "strftime", "localtime"] # time.h +allowed_words += [ # system.h + "int64", + "dbg_assert", "dbg_msg", "dbg_break", "dbg_logger_stdout", "dbg_logger_debugger", "dbg_logger_file", + "mem_alloc", "mem_zero", "mem_free", "mem_copy", "mem_move", "mem_comp", "mem_stats", "total_allocations", "allocated", + "thread_create", "thread_sleep", "lock_wait", "lock_create", "lock_release", "lock_destroy", "swap_endian", + "io_open", "io_read", "io_read", "io_write", "io_flush", "io_close", "io_seek", "io_skip", "io_tell", "io_length", + "str_comp", "str_length", "str_quickhash", "str_format", "str_copy", "str_comp_nocase", "str_sanitize", "str_append", + "str_comp_num", "str_find_nocase", "str_sanitize_strong", "str_uppercase", "str_toint", "str_tofloat", + "str_utf8_encode", "str_utf8_rewind", "str_utf8_forward", "str_utf8_decode", "str_sanitize_cc", "str_skip_whitespaces", + "fs_makedir", "fs_listdir", "fs_storage_path", "fs_is_dir", + "net_init", "net_addr_comp", "net_host_lookup", "net_addr_str", "type", "port", "net_addr_from_str", + "net_udp_create", "net_udp_send", "net_udp_recv", "net_udp_close", "net_socket_read_wait", + "net_stats", "sent_bytes", "recv_bytes", "recv_packets", "sent_packets", + "time_get", "time_freq", "time_timestamp"] + +allowed_words += ["vec2", "vec3", "vec4", "round", "clamp", "length", "dot", "normalize", "random_float", "mix", "distance", "min", + "closest_point_on_line", "max", "absolute"] # math.hpp +allowed_words += [ # tl + "array", "sorted_array", "string", + "all", "sort", "add", "remove_index", "remove", "delete_all", "set_size", + "base_ptr", "size", "swap", "empty", "front", "pop_front", "find_binary", "find_linear", "clear", "range", "end", "cstr", + "partition_linear", "partition_binary"] +allowed_words += ["fx2f", "f2fx"] # fixed point math + +def CheckIdentifier(ident): + return False + +class Checker: + def CheckStart(self, checker, filename): + pass + def CheckLine(self, checker, line): + pass + def CheckEnd(self, checker): + pass + +class FilenameExtentionChecker(Checker): + def __init__(self): + self.allowed = [".cpp", ".h"] + def CheckStart(self, checker, filename): + ext = os.path.splitext(filename)[1] + if not ext in self.allowed: + checker.Error("file extention '%s' is not allowed" % ext) + +class IncludeChecker(Checker): + def __init__(self): + self.disallowed_headers = ["stdio.h", "stdlib.h", "string.h", "memory.h"] + def CheckLine(self, checker, line): + if "#include" in line: + include_file = "" + if '<' in line: + include_file = line.split('<')[1].split(">")[0] + #if not "/" in include_file: + # checker.Error("%s is not allowed" % include_file) + elif '"' in line: + include_file = line.split('"')[1] + + #print include_file + if include_file in self.disallowed_headers: + checker.Error("%s is not allowed" % include_file) + +class HeaderGuardChecker(Checker): + def CheckStart(self, checker, filename): + self.check = ".h" in filename + self.guard = "#ifndef " + filename[4:].replace("/", "_").replace(".hpp", "").replace(".h", "").upper() + "_H" + def CheckLine(self, checker, line): + if self.check: + #if "#" in line: + self.check = False + #if not self.check: + if line.strip() == self.guard: + pass + else: + checker.Error("malformed or missing header guard. Should be '%s'" % self.guard) + +class CommentChecker(Checker): + def CheckLine(self, checker, line): + if line.strip()[-2:] == "*/" and "/*" in line: + checker.Error("single line multiline comment") + +class FileChecker: + def __init__(self): + self.checkers = [] + self.checkers += [FilenameExtentionChecker()] + self.checkers += [HeaderGuardChecker()] + self.checkers += [IncludeChecker()] + self.checkers += [CommentChecker()] + + def Error(self, errormessage): + self.current_errors += [(self.current_line, errormessage)] + + def CheckLine(self, line): + for c in self.checkers: + c.CheckLine(self, line) + return True + + def CheckFile(self, filename): + self.current_file = filename + self.current_line = 0 + self.current_errors = [] + for c in self.checkers: + c.CheckStart(self, filename) + + for line in file(filename).readlines(): + self.current_line += 1 + if "ignore_check" in line: + continue + self.CheckLine(line) + + for c in self.checkers: + c.CheckEnd(self) + + def GetErrors(self): + return self.current_errors + +def cstrip(lines): + d = "" + for l in lines: + if "ignore_convention" in l: + continue + l = re.sub("^[\t ]*#.*", "", l) + l = re.sub("//.*", "", l) + l = re.sub('\".*?\"', '"String"', l) # remove strings + d += l.strip() + " " + d = re.sub('\/\*.*?\*\/', "", d) # remove /* */ comments + d = d.replace("\t", " ") # tab to space + d = re.sub(" *", " ", d) # remove double spaces + #d = re.sub("", "", d) # remove /* */ comments + + d = d.strip() + + # this eats up cases like 'n {' + i = 1 + while i < len(d)-2: + if d[i] == ' ': + if not (d[i-1] in alphanum and d[i+1] in alphanum): + d = d[:i] + d[i+1:] + i += 1 + return d + +#def stripstrings(data): +# return re.sub('\".*?\"', 'STRING', data) + +def get_identifiers(data): + idents = {} + data = " "+data+" " + regexp = re.compile("[^a-zA-Z0-9_][a-zA-Z_][a-zA-Z0-9_]+[^a-zA-Z0-9_]") + start = 0 + while 1: + m = regexp.search(data, start) + + if m == None: + break + start = m.end()-1 + name = data[m.start()+1:m.end()-1] + if name in idents: + idents[name] += 1 + else: + idents[name] = 1 + return idents + +grand_total = 0 +grand_offenders = 0 + +gen_html = 1 + +if gen_html: + print "" + print '' + print "" + print "" + + + + print '
' + + print '
' + print 'teeworlds logo' + print '
' + + print '' + + print '
 
' + print '
' + print '
' + + print '

' + print '

Code Refactoring Progress

' + print '''This is generated by a script that find identifiers in the code + that doesn't conform to the code standard. Right now it only shows headers + because they need to be fixed before we can do the rest of the source. + This is a ROUGH estimate of the progress''' + print '

' + + print '

' + print '' + #print "" + +line_order = 1 +total_files = 0 +complete_files = 0 +total_errors = 0 + +for (root,dirs,files) in os.walk("src"): + for filename in files: + filename = os.path.join(root, filename) + if "/." in filename or "/external/" in filename or "/base/" in filename or "/generated/" in filename: + continue + if "src/osxlaunch/client.h" in filename: # ignore this file, ObjC file + continue + if "e_config_variables.h" in filename: # ignore config files + continue + if "src/game/variables.hpp" in filename: # ignore config files + continue + + if not (".hpp" in filename or ".h" in filename or ".cpp" in filename): + continue + + #total_files += 1 + + #if not "src/engine/client/ec_client.cpp" in filename: + # continue + + f = FileChecker() + f.CheckFile(filename) + num_errors = len(f.GetErrors()) + total_errors += num_errors + + if num_errors: + print '' % (filename, num_errors), + for line, msg in f.GetErrors(): + print '' % (line, msg) + #print '
%#FileOffenders
%s, %d errors
%d%s
' + #GetErrors() + + + + + if 0: + text = cstrip(file(filename).readlines()) # remove all preprocessor stuff and comments + #text = stripstrings(text) # remove strings (does not solve all cases however) + #print text + + idents = get_identifiers(text) + offenders = 0 + total = 0 + offender_list = {} + for name in idents: + #print name + if len(name) <= 2: # skip things that are too small + continue + if name in cpp_keywords: # skip keywords + continue + if name in allowed_words: # skip allowed keywords + continue + + total += idents[name] + if name != name.lower(): # strip names that are not only lower case + continue + offender_list[name] = idents[name] + if not gen_html: + print "[%d] %s"%(idents[name], name) + offenders += idents[name] + + grand_total += total + grand_offenders += offenders + + if total == 0: + total = 1 + + line_order = -line_order + + + done = int((1-(offenders / float(total))) * 100) + if done == 100: + complete_files += 1 + + if done != 100 and gen_html: + color = "#ffa0a0" + if done > 20: + color = "#ffd080" + if done > 50: + color = "#ffff80" + if done > 75: + color = "#e0ff80" + if done == 100: + color = "#80ff80" + + line_color = "#f0efd5" + if line_order > 0: + line_color = "#ffffff" + + offender_string = "" + count = 0 + for name in offender_list: + count += 1 + offender_string += "[%d]%s " % (offender_list[name], name) + + if count%5 == 0: + offender_string += "
" + + print '' % line_color, + print '' % (color, done, offenders, filename), + print '' % offender_string + print "" + count = 0 + +if gen_html: + print "
%d%%%d%s%s
" + + print "

%d errors

" % total_errors + + + if 0: + print "

%.1f%% Identifiers done

" % ((1-(grand_offenders / float(grand_total))) * 100) + print "%d left of %d" % (grand_offenders, grand_total) + print "

%.1f%% Files done

" % ((complete_files / float(total_files)) * 100) + print "%d left of %d" % (total_files-complete_files, total_files) + + print "

" + print "
" + print '
' + print '
' + + print '
 
' + print '
' + + print "" diff --git a/scripts/tw_api.py b/scripts/tw_api.py new file mode 100644 index 000000000..c39ad3d1c --- /dev/null +++ b/scripts/tw_api.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +# coding: utf-8 +from socket import socket, AF_INET, SOCK_DGRAM +import sys +import threading +import time + +import random + +NUM_MASTERSERVERS = 4 +MASTERSERVER_PORT = 8283 + + +TIMEOUT = 2 +BUFFER_SIZE = 4096 +NUM_RETRIES = 3 + + +# retries after waiting a specific time if the simple retry method failed. +# SLEEP_SECS is multiplied with 2 on every retry +FORCE_SLEEP = True +SLEEP_SECS = 2.0 +NUM_SLEEP_RETRIES = 2 + +# src/mastersrv/mastersrv.h +PACKET_GETLIST = b"\xff\xff\xff\xffreq2" +PACKET_LIST = b"\xff\xff\xff\xfflis2" + +PACKET_GETINFO = b"\xff\xff\xff\xffgie3" +PACKET_INFO = b"\xff\xff\xff\xffinf3" + + +# see CNetBase::SendControlMsgWithToken +def pack_control_msg_with_token(token_srv,token_cl): + NET_PACKETFLAG_CONTROL = 1 + NET_CTRLMSG_TOKEN = 5 + NET_TOKENREQUEST_DATASIZE = 512 + b = [0]*(4 + 3 + NET_TOKENREQUEST_DATASIZE) + # Header + b[0] = (NET_PACKETFLAG_CONTROL<<2)&0xfc + b[3] = (token_srv >> 24) & 0xff + b[4] = (token_srv >> 16) & 0xff + b[5] = (token_srv >> 8) & 0xff + b[6] = (token_srv) & 0xff + # Data + b[7] = NET_CTRLMSG_TOKEN + b[8] = (token_cl >> 24) & 0xff + b[9] = (token_cl >> 16) & 0xff + b[10] = (token_cl >> 8) & 0xff + b[11] = (token_cl) & 0xff + return bytes(b) + + +def unpack_control_msg_with_token(msg): + b = list(msg) + token_cl = (b[3] << 24) + (b[4] << 16) + (b[5] << 8) + (b[6]) + token_srv = (b[8] << 24) + (b[9] << 16) + (b[10] << 8) + (b[11]) + return token_cl,token_srv + + +# CNetBase::SendPacketConnless +def header_connless(token_srv, token_cl): + NET_PACKETFLAG_CONNLESS = 8 + NET_PACKETVERSION = 1 + b = [0]*9 + # Header + b[0] = ((NET_PACKETFLAG_CONNLESS<<2)&0xfc) | (NET_PACKETVERSION&0x03) + b[1] = (token_srv >> 24) & 0xff + b[2] = (token_srv >> 16) & 0xff + b[3] = (token_srv >> 8) & 0xff + b[4] = (token_srv) & 0xff + # ResponseToken + b[5] = (token_cl >> 24) & 0xff + b[6] = (token_cl >> 16) & 0xff + b[7] = (token_cl >> 8) & 0xff + b[8] = (token_cl) & 0xff + return bytes(b) + + +# CVariableInt::Unpack from src/engine/shared/compression.cpp +def unpack_int(b): + l = list(b[:5]) + i = 0 + Sign = (l[i]>>6)&1 + res = l[i] & 0x3F + + for _ in (0,): + if not (l[i]&0x80): + break + i+=1 + res |= (l[i]&(0x7F))<<(6) + + if not (l[i]&0x80): + break + i+=1 + res |= (l[i]&(0x7F))<<(6+7) + + if not (l[i]&0x80): + break + i+=1 + res |= (l[i]&(0x7F))<<(6+7+7) + + if not (l[i]&0x80): + break + i+=1 + res |= (l[i]&(0x7F))<<(6+7+7+7) + + i += 1 + res ^= -Sign + return res, b[i:] + + +class Server_Info(threading.Thread): + + def __init__(self, address): + self.address = address + self.info = None + self.finished = False + threading.Thread.__init__(self, target = self.run) + + def __str__(self): + return str(self.info) + + def __getitem__(self, key): + return self.info[key] + + def run(self): + self.info = get_server_info(self.address) + self.finished = True + + +def get_server_info(address): + + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT) + + # function definition + def send_token(sock, address, timeout=TIMEOUT): + token = random.randrange(0x100000000) + + # Token request + sock.sendto(pack_control_msg_with_token(-1,token),address) + + # send and receive + sock.settimeout(timeout) + data, _ = sock.recvfrom(BUFFER_SIZE) + + # calculate expected token + token_cl, token_srv = unpack_control_msg_with_token(data) + + # return, whether the correct token was received + return token_cl == token, token_cl, token_srv + + + retries = NUM_RETRIES + token_success, token_cl, token_srv = send_token(sock, address) + + while not token_success and retries > 0: + retries -= 1 + token_success, token_cl, token_srv = send_token(sock, address, sock.gettimeout() * 2) + + sock.settimeout(TIMEOUT) # reset to default value + + if retries == 0: + raise ValueError(f"Failed to retrieve token from: {address}") + + # function definition + def send_header(sock, address, token_cl, token_srv, timeout=TIMEOUT, sleep_secs = None): + # Get info request + sock.sendto(header_connless(token_srv, token_cl) + PACKET_GETINFO + b'\x00', address) + sock.settimeout(timeout) + if isinstance(sleep_secs, int): + time.sleep(sleep_secs) + data, _ = sock.recvfrom(BUFFER_SIZE) + + head = header_connless(token_cl, token_srv) + PACKET_INFO + b'\x00' + + received_head = data[:len(head)] # get header + data = data[len(head):] # skip header + + return received_head == head, data # we don't need the header + + + data_success, data = send_header(sock, address, token_cl, token_srv) + retries = NUM_RETRIES + + while not data_success and retries > 0: + retries -= 1 + data_success, data = send_header(sock, address, token_cl, token_srv, sock.gettimeout() * 2) + + sock.settimeout(TIMEOUT) # reset to default value + + # fast way didn't work, let's try the slow way + if FORCE_SLEEP and not data_success and retries == 0: + retries = NUM_SLEEP_RETRIES + sleep_secs = SLEEP_SECS / 2.0 + + while not data_success and retries > 0: + retries -= 1 + sleep_secs *= 2 + data_success, data = send_header(sock, address, token_cl, token_srv, sock.gettimeout() * 2.0, sleep_secs=sleep_secs) + if not data_success and retries == 0: + raise ValueError(f"Failed to retrieve server info from {address}") + + elif not data_success and retries == 0: + raise ValueError(f"Failed to retrieve server info from {address}") + + slots = data.split(b"\x00", maxsplit=5) + + server_info = {} + server_info["address"] = address + server_info["version"] = slots[0].decode() + server_info["name"] = slots[1].decode() + server_info["hostname"] = slots[2].decode() + server_info["map"] = slots[3].decode() + server_info["gametype"] = slots[4].decode() + data = slots[5] + + # these integers should fit in one byte each + server_info["flags"], server_info["skill"] = tuple(data[:2]) + data = data[2:] + + server_info["num_players"], data = unpack_int(data) + server_info["max_players"], data = unpack_int(data) + server_info["num_clients"], data = unpack_int(data) + server_info["max_clients"], data = unpack_int(data) + server_info["players"] = [] + + for _ in range(server_info["num_clients"]): + player = {} + slots = data.split(b"\x00", maxsplit=2) + player["name"] = slots[0].decode() + player["clan"] = slots[1].decode() + data = slots[2] + player["country"], data = unpack_int(data) + player["score"], data = unpack_int(data) + player["player"], data = unpack_int(data) + server_info["players"].append(player) + + return server_info + except AssertionError as e: + print(*e.args) + except OSError as e: # Timeout + #print('> Server %s did not answer' % (address,)) + pass + except ValueError as e: + print(e) + except Exception as e: + print(e) + # print('> Server %s did something wrong here' % (address,)) + # import traceback + # traceback.print_exc() + finally: + sock.close() # socket is closed in any case + return None + + +class Master_Server_Info(threading.Thread): + + def __init__(self, address): + self.address = address + self.servers = [] + self.finished = False + threading.Thread.__init__(self, target = self.run) + + def run(self): + self.servers = get_list(self.address) + self.finished = True + + +def get_list(address): + servers = [] + answer = False + + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT) + + token = random.randrange(0x100000000) + + # Token request + sock.sendto(pack_control_msg_with_token(-1,token),address) + data, addr = sock.recvfrom(BUFFER_SIZE) + token_cl, token_srv = unpack_control_msg_with_token(data) + assert token_cl == token, "Master %s send wrong token: %d (%d expected)" % (address, token_cl, token) + answer = True + + # Get list request + sock.sendto(header_connless(token_srv, token_cl) + PACKET_GETLIST, addr) + head = header_connless(token_cl, token_srv) + PACKET_LIST + + while 1: + data, addr = sock.recvfrom(BUFFER_SIZE) + # Header should keep consistent + assert data[:len(head)] == head, "Master %s list header mismatch: %r != %r (expected)" % (address, data[:len(head)], head) + + data = data[len(head):] + num_servers = len(data) // 18 + + for n in range(0, num_servers): + # IPv4 + if data[n*18:n*18+12] == b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff": + ip = ".".join(map(str, data[n*18+12:n*18+16])) + # IPv6 + else: + ip = ":".join(map(str, data[n*18:n*18+16])) + port = ((data[n*18+16])<<8) + data[n*18+17] + servers += [(ip, port)] + + except AssertionError as e: + print(*e.args) + except OSError as e: # Timeout + if not answer: + print('> Master %s did not answer' % (address,)) + except Exception as e: + # import traceback + # traceback.print_exc() + print(e) + finally: + sock.close() + + return servers + + +if __name__ == '__main__': + master_servers = [] + + for i in range(1, NUM_MASTERSERVERS+1): + m = Master_Server_Info(("master%d.teeworlds.com"%i, MASTERSERVER_PORT)) + master_servers.append(m) + m.start() + + servers = set() + + while len(master_servers) != 0: + master_servers[0].join() + + if master_servers[0].finished == True: + if master_servers[0].servers: + servers.update(master_servers[0].servers) + del master_servers[0] + + + servers_info = [] + + print(len(servers), "servers") + + for server in servers: + s = Server_Info(server) + servers_info.append(s) + s.start() + + num_players = 0 + num_clients = 0 + num_botplayers = 0 + num_botspectators = 0 + + while len(servers_info) != 0: + servers_info[0].join() + + if servers_info[0].finished == True: + if servers_info[0].info: + server_info = servers_info[0].info + # check num/max validity + if server_info["num_players"] > server_info["max_players"] \ + or server_info["num_clients"] > server_info["max_clients"] \ + or server_info["max_players"] > server_info["max_clients"] \ + or server_info["num_players"] < 0 \ + or server_info["num_clients"] < 0 \ + or server_info["max_clients"] < 0 \ + or server_info["max_players"] < 0 \ + or server_info["max_clients"] > 64: + server_info["bad"] = 'invalid num/max' + print('> Server %s has %s' % (server_info["address"], server_info["bad"])) + # check actual purity + elif server_info["gametype"] in ('DM', 'TDM', 'CTF', 'LMS', 'LTS') \ + and server_info["max_players"] > 16: + server_info["bad"] = 'too many players for vanilla' + print('> Server %s has %s' % (server_info["address"], server_info["bad"])) + + else: + num_players += server_info["num_players"] + num_clients += server_info["num_clients"] + for p in servers_info[0].info["players"]: + if p["player"] == 2: + num_botplayers += 1 + if p["player"] == 3: + num_botspectators += 1 + + del servers_info[0] + + + print('%d players (%d bots) and %d spectators (%d bots)' % (num_players, num_botplayers, num_clients - num_players, num_botspectators)) diff --git a/scripts/twlib.py b/scripts/twlib.py new file mode 100644 index 000000000..91ecaa100 --- /dev/null +++ b/scripts/twlib.py @@ -0,0 +1,23 @@ +import sys +if sys.version_info[0] == 2: + import urllib + url_lib = urllib +elif sys.version_info[0] == 3: + import urllib.request + url_lib = urllib.request + +def fetch_file(url): + print("trying %s" % url) + try: + local = dict(url_lib.urlopen(url).info()) + if "Content-Disposition" in local: + key_name = "Content-Disposition" + elif "content-disposition" in local: + key_name = "content-disposition" + else: + return False + local = local[key_name].split("=")[1] + url_lib.urlretrieve(url, local) + return local + except IOError: + return False diff --git a/src/base/color.h b/src/base/color.h new file mode 100644 index 000000000..e786fa8c5 --- /dev/null +++ b/src/base/color.h @@ -0,0 +1,174 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_COLOR_H +#define BASE_COLOR_H + +#include "vmath.h" + +/* + Title: Color handling +*/ + +/* + Function: HueToRgb + Converts Hue to RGB +*/ +inline float HueToRgb(float v1, float v2, float h) +{ + if(h < 0.0f) h += 1; + if(h > 1.0f) h -= 1; + if((6.0f * h) < 1.0f) return v1 + (v2 - v1) * 6.0f * h; + if((2.0f * h) < 1.0f) return v2; + if((3.0f * h) < 2.0f) return v1 + (v2 - v1) * ((2.0f/3.0f) - h) * 6.0f; + return v1; +} + +/* + Function: HslToRgb + Converts HSL to RGB +*/ +inline vec3 HslToRgb(vec3 HSL) +{ + if(HSL.s == 0.0f) + return vec3(HSL.l, HSL.l, HSL.l); + + float v2 = HSL.l < 0.5f ? HSL.l * (1.0f + HSL.s) : (HSL.l+HSL.s) - (HSL.s*HSL.l); + float v1 = 2.0f * HSL.l - v2; + return vec3(HueToRgb(v1, v2, HSL.h + (1.0f/3.0f)), HueToRgb(v1, v2, HSL.h), HueToRgb(v1, v2, HSL.h - (1.0f/3.0f))); +} + +/* + Function: HexToRgba + Converts Hex to RGBA + + Remarks: Hex should be RGBA8 +*/ +inline vec4 HexToRgba(int hex) +{ + vec4 c; + c.r = ((hex >> 24) & 0xFF) / 255.0f; + c.g = ((hex >> 16) & 0xFF) / 255.0f; + c.b = ((hex >> 8) & 0xFF) / 255.0f; + c.a = (hex & 0xFF) / 255.0f; + return c; +} + +/* + Function: HsvToRgb + Converts HSV to RGB +*/ +inline vec3 HsvToRgb(vec3 hsv) +{ + int h = int(hsv.x * 6.0f); + float f = hsv.x * 6.0f - h; + float p = hsv.z * (1.0f - hsv.y); + float q = hsv.z * (1.0f - hsv.y * f); + float t = hsv.z * (1.0f - hsv.y * (1.0f - f)); + + vec3 rgb = vec3(0.0f, 0.0f, 0.0f); + + switch(h % 6) + { + case 0: + rgb.r = hsv.z; + rgb.g = t; + rgb.b = p; + break; + + case 1: + rgb.r = q; + rgb.g = hsv.z; + rgb.b = p; + break; + + case 2: + rgb.r = p; + rgb.g = hsv.z; + rgb.b = t; + break; + + case 3: + rgb.r = p; + rgb.g = q; + rgb.b = hsv.z; + break; + + case 4: + rgb.r = t; + rgb.g = p; + rgb.b = hsv.z; + break; + + case 5: + rgb.r = hsv.z; + rgb.g = p; + rgb.b = q; + break; + } + + return rgb; +} + +/* + Function: RgbToHsv + Converts RGB to HSV +*/ +inline vec3 RgbToHsv(vec3 rgb) +{ + float h_min = minimum(minimum(rgb.r, rgb.g), rgb.b); + float h_max = maximum(maximum(rgb.r, rgb.g), rgb.b); + + // hue + float hue = 0.0f; + + if(h_max == h_min) + hue = 0.0f; + else if(h_max == rgb.r) + hue = (rgb.g-rgb.b) / (h_max-h_min); + else if(h_max == rgb.g) + hue = 2.0f + (rgb.b-rgb.r) / (h_max-h_min); + else + hue = 4.0f + (rgb.r-rgb.g) / (h_max-h_min); + + hue /= 6.0f; + + if(hue < 0.0f) + hue += 1.0f; + + // saturation + float s = 0.0f; + if(h_max != 0.0f) + s = (h_max - h_min)/h_max; + + // value + float v = h_max; + + return vec3(hue, s, v); +} + +inline float RgbToLabH(float val) +{ + return val > 0.008856f ? powf(val, 0.333333f) : (7.787f*val + 0.137931f); +} + +/* + Function: RgbToLab + Converts RGB to Lab +*/ +inline vec3 RgbToLab(vec3 rgb) +{ + vec3 adapt(0.950467f, 1, 1.088969f); + vec3 xyz( + 0.412424f * rgb.r + 0.357579f * rgb.g + 0.180464f * rgb.b, + 0.212656f * rgb.r + 0.715158f * rgb.g + 0.0721856f * rgb.b, + 0.0193324f * rgb.r + 0.119193f * rgb.g + 0.950444f * rgb.b + ); + + return vec3( + 116 * RgbToLabH(xyz.y / adapt.y) - 16, + 500 * (RgbToLabH(xyz.x / adapt.x) - RgbToLabH(xyz.y / adapt.y)), + 200 * (RgbToLabH(xyz.y / adapt.y) - RgbToLabH(xyz.z / adapt.z)) + ); +} + +#endif diff --git a/src/base/detect.h b/src/base/detect.h new file mode 100644 index 000000000..50931623e --- /dev/null +++ b/src/base/detect.h @@ -0,0 +1,164 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_DETECT_H +#define BASE_DETECT_H + +/* + this file detected the family, platform and architecture + to compile for. +*/ + +/* platforms */ + +/* windows Family */ +#if defined(WIN64) || defined(_WIN64) + /* Hmm, is this IA64 or x86-64? */ + #define CONF_FAMILY_WINDOWS 1 + #define CONF_FAMILY_STRING "windows" + #define CONF_PLATFORM_WIN64 1 + #define CONF_PLATFORM_STRING "win64" +#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) + #define CONF_FAMILY_WINDOWS 1 + #define CONF_FAMILY_STRING "windows" + #define CONF_PLATFORM_WIN32 1 + #define CONF_PLATFORM_STRING "win32" +#endif + +/* unix family */ +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_FREEBSD 1 + #define CONF_PLATFORM_STRING "freebsd" +#endif + +#if defined(__NetBSD__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_NETBSD 1 + #define CONF_PLATFORM_STRING "netbsd" +#endif + +#if defined(__OpenBSD__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_OPENBSD 1 + #define CONF_PLATFORM_STRING "openbsd" +#endif + +#if defined(__LINUX__) || defined(__linux__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_LINUX 1 + #define CONF_PLATFORM_STRING "linux" +#endif + +#if defined(__GNU__) || defined(__gnu__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_HURD 1 + #define CONF_PLATFORM_STRING "gnu" +#endif + +#if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_MACOSX 1 + #define CONF_PLATFORM_STRING "macosx" +#endif + +#if defined(__sun) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_SOLARIS 1 + #define CONF_PLATFORM_STRING "solaris" +#endif + +/* beos family */ +#if defined(__BeOS) || defined(__BEOS__) + #define CONF_FAMILY_BEOS 1 + #define CONF_FAMILY_STRING "beos" + #define CONF_PLATFORM_BEOS 1 + #define CONF_PLATFORM_STRING "beos" +#endif + + +/* use gcc endianness definitions when available */ +#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun) + #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + #include + #else + #include + #endif + + #if __BYTE_ORDER == __LITTLE_ENDIAN + #define CONF_ARCH_ENDIAN_LITTLE 1 + #elif __BYTE_ORDER == __BIG_ENDIAN + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + + +/* architectures */ +#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32) + #define CONF_ARCH_IA32 1 + #define CONF_ARCH_STRING "ia32" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__ia64__) || defined(_M_IA64) + #define CONF_ARCH_IA64 1 + #define CONF_ARCH_STRING "ia64" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64) + #define CONF_ARCH_AMD64 1 + #define CONF_ARCH_STRING "amd64" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__powerpc__) || defined(__ppc__) + #define CONF_ARCH_PPC 1 + #define CONF_ARCH_STRING "ppc" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + +#if defined(__sparc__) + #define CONF_ARCH_SPARC 1 + #define CONF_ARCH_STRING "sparc" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + +#if defined(__arm__) + #define CONF_ARCH_ARM 1 + #define CONF_ARCH_STRING "arm" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + + +#ifndef CONF_FAMILY_STRING +#define CONF_FAMILY_STRING "unknown" +#endif + +#ifndef CONF_PLATFORM_STRING +#define CONF_PLATFORM_STRING "unknown" +#endif + +#ifndef CONF_ARCH_STRING +#define CONF_ARCH_STRING "unknown" +#endif + +#endif diff --git a/src/base/hash.c b/src/base/hash.c new file mode 100644 index 000000000..6c091c564 --- /dev/null +++ b/src/base/hash.c @@ -0,0 +1,66 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "hash.h" +#include "hash_ctxt.h" + +#include "system.h" + +static void digest_str(const unsigned char *digest, size_t digest_len, char *str, size_t max_len) +{ + unsigned i; + if(max_len > digest_len * 2 + 1) + { + max_len = digest_len * 2 + 1; + } + str[max_len - 1] = 0; + max_len -= 1; + for(i = 0; i < max_len; i++) + { + static const char HEX[] = "0123456789abcdef"; + int index = i / 2; + if(i % 2 == 0) + { + str[i] = HEX[digest[index] >> 4]; + } + else + { + str[i] = HEX[digest[index] & 0xf]; + } + } +} + +SHA256_DIGEST sha256(const void *message, size_t message_len) +{ + SHA256_CTX ctxt; + sha256_init(&ctxt); + sha256_update(&ctxt, message, message_len); + return sha256_finish(&ctxt); +} + +void sha256_str(SHA256_DIGEST digest, char *str, size_t max_len) +{ + digest_str(digest.data, sizeof(digest.data), str, max_len); +} + +int sha256_comp(SHA256_DIGEST digest1, SHA256_DIGEST digest2) +{ + return mem_comp(digest1.data, digest2.data, sizeof(digest1.data)); +} + +MD5_DIGEST md5(const void *message, size_t message_len) +{ + MD5_CTX ctxt; + md5_init(&ctxt); + md5_update(&ctxt, message, message_len); + return md5_finish(&ctxt); +} + +void md5_str(MD5_DIGEST digest, char *str, size_t max_len) +{ + digest_str(digest.data, sizeof(digest.data), str, max_len); +} + +int md5_comp(MD5_DIGEST digest1, MD5_DIGEST digest2) +{ + return mem_comp(digest1.data, digest2.data, sizeof(digest1.data)); +} diff --git a/src/base/hash.h b/src/base/hash.h new file mode 100644 index 000000000..e3153d590 --- /dev/null +++ b/src/base/hash.h @@ -0,0 +1,66 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_HASH_H +#define BASE_HASH_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + SHA256_DIGEST_LENGTH=256/8, + SHA256_MAXSTRSIZE=2*SHA256_DIGEST_LENGTH+1, + MD5_DIGEST_LENGTH=128/8, + MD5_MAXSTRSIZE=2*MD5_DIGEST_LENGTH+1, +}; + +typedef struct +{ + unsigned char data[SHA256_DIGEST_LENGTH]; +} SHA256_DIGEST; + +typedef struct +{ + unsigned char data[MD5_DIGEST_LENGTH]; +} MD5_DIGEST; + +SHA256_DIGEST sha256(const void *message, size_t message_len); +void sha256_str(SHA256_DIGEST digest, char *str, size_t max_len); +int sha256_from_str(SHA256_DIGEST *out, const char *str); +int sha256_comp(SHA256_DIGEST digest1, SHA256_DIGEST digest2); + +MD5_DIGEST md5(const void *message, size_t message_len); +void md5_str(MD5_DIGEST digest, char *str, size_t max_len); +int md5_from_str(MD5_DIGEST *out, const char *str); +int md5_comp(MD5_DIGEST digest1, MD5_DIGEST digest2); + +static const SHA256_DIGEST SHA256_ZEROED = {{0}}; +static const MD5_DIGEST MD5_ZEROED = {{0}}; + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +inline bool operator==(const SHA256_DIGEST &that, const SHA256_DIGEST &other) +{ + return sha256_comp(that, other) == 0; +} +inline bool operator!=(const SHA256_DIGEST &that, const SHA256_DIGEST &other) +{ + return !(that == other); +} +inline bool operator==(const MD5_DIGEST &that, const MD5_DIGEST &other) +{ + return md5_comp(that, other) == 0; +} +inline bool operator!=(const MD5_DIGEST &that, const MD5_DIGEST &other) +{ + return !(that == other); +} +#endif + +#endif // BASE_HASH_H diff --git a/src/base/hash_bundled.c b/src/base/hash_bundled.c new file mode 100644 index 000000000..23a4f73b8 --- /dev/null +++ b/src/base/hash_bundled.c @@ -0,0 +1,21 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#if !defined(CONF_OPENSSL) + +#include "hash_ctxt.h" + +#include + +void md5_update(MD5_CTX *ctxt, const void *data, size_t data_len) +{ + md5_append(ctxt, data, data_len); +} + +MD5_DIGEST md5_finish(MD5_CTX *ctxt) +{ + MD5_DIGEST result; + md5_finish_(ctxt, result.data); + return result; +} + +#endif diff --git a/src/base/hash_ctxt.h b/src/base/hash_ctxt.h new file mode 100644 index 000000000..1c6910379 --- /dev/null +++ b/src/base/hash_ctxt.h @@ -0,0 +1,45 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_HASH_CTXT_H +#define BASE_HASH_CTXT_H + +#include "hash.h" +#include + +#if defined(CONF_OPENSSL) +#include +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(CONF_OPENSSL) +// SHA256_CTX is defined in +#else +typedef struct +{ + uint64_t length; + uint32_t state[8]; + uint32_t curlen; + unsigned char buf[64]; +} SHA256_CTX; +typedef md5_state_t MD5_CTX; +#endif + +void sha256_init(SHA256_CTX *ctxt); +void sha256_update(SHA256_CTX *ctxt, const void *data, size_t data_len); +SHA256_DIGEST sha256_finish(SHA256_CTX *ctxt); + +void md5_init(MD5_CTX *ctxt); +void md5_update(MD5_CTX *ctxt, const void *data, size_t data_len); +MD5_DIGEST md5_finish(MD5_CTX *ctxt); + +#ifdef __cplusplus +} +#endif + +#endif // BASE_HASH_CTXT_H diff --git a/src/base/hash_libtomcrypt.c b/src/base/hash_libtomcrypt.c new file mode 100755 index 000000000..50bf770d4 --- /dev/null +++ b/src/base/hash_libtomcrypt.c @@ -0,0 +1,202 @@ +// SHA-256. Adapted from https://github.com/kalven/sha-2, which was adapted +// from LibTomCrypt. This code is Public Domain. + +#if !defined(CONF_OPENSSL) + +#include "hash_ctxt.h" + +#include +#include +#include + +typedef uint32_t u32; +typedef uint64_t u64; +typedef SHA256_CTX sha256_state; + +static const u32 K[64] = +{ + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + +static u32 min(u32 x, u32 y) +{ + return x < y ? x : y; +} + +static u32 load32(const unsigned char* y) +{ + return ((u32)y[0] << 24) | ((u32)y[1] << 16) | ((u32)y[2] << 8) | ((u32)y[3] << 0); +} + +static void store64(u64 x, unsigned char* y) +{ + int i; + for(i = 0; i != 8; ++i) + y[i] = (x >> ((7-i) * 8)) & 255; +} + +static void store32(u32 x, unsigned char* y) +{ + int i; + for(i = 0; i != 4; ++i) + y[i] = (x >> ((3-i) * 8)) & 255; +} + +static u32 Ch(u32 x, u32 y, u32 z) { return z ^ (x & (y ^ z)); } +static u32 Maj(u32 x, u32 y, u32 z) { return ((x | y) & z) | (x & y); } +static u32 Rot(u32 x, u32 n) { return (x >> (n & 31)) | (x << (32 - (n & 31))); } +static u32 Sh(u32 x, u32 n) { return x >> n; } +static u32 Sigma0(u32 x) { return Rot(x, 2) ^ Rot(x, 13) ^ Rot(x, 22); } +static u32 Sigma1(u32 x) { return Rot(x, 6) ^ Rot(x, 11) ^ Rot(x, 25); } +static u32 Gamma0(u32 x) { return Rot(x, 7) ^ Rot(x, 18) ^ Sh(x, 3); } +static u32 Gamma1(u32 x) { return Rot(x, 17) ^ Rot(x, 19) ^ Sh(x, 10); } + +static void sha_compress(sha256_state* md, const unsigned char* buf) +{ + u32 S[8], W[64], t0, t1, t; + int i; + + // Copy state into S + for(i = 0; i < 8; i++) + S[i] = md->state[i]; + + // Copy the state into 512-bits into W[0..15] + for(i = 0; i < 16; i++) + W[i] = load32(buf + (4*i)); + + // Fill W[16..63] + for(i = 16; i < 64; i++) + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + + // Compress + #define RND(a, b, c, d, e, f, g, h, i) \ + { \ + t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ + t1 = Sigma0(a) + Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; \ + } + + for(i = 0; i < 64; ++i) + { + RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i); + t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; + S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; + } + + // Feedback + for(i = 0; i < 8; i++) + md->state[i] = md->state[i] + S[i]; +} + +// Public interface + +static void sha_init(sha256_state* md) +{ + md->curlen = 0; + md->length = 0; + md->state[0] = 0x6A09E667UL; + md->state[1] = 0xBB67AE85UL; + md->state[2] = 0x3C6EF372UL; + md->state[3] = 0xA54FF53AUL; + md->state[4] = 0x510E527FUL; + md->state[5] = 0x9B05688CUL; + md->state[6] = 0x1F83D9ABUL; + md->state[7] = 0x5BE0CD19UL; +} + +static void sha_process(sha256_state* md, const void* src, u32 inlen) +{ + const u32 block_size = 64; + const unsigned char* in = src; + + while(inlen > 0) + { + if(md->curlen == 0 && inlen >= block_size) + { + sha_compress(md, in); + md->length += block_size * 8; + in += block_size; + inlen -= block_size; + } + else + { + u32 n = min(inlen, (block_size - md->curlen)); + memcpy(md->buf + md->curlen, in, n); + md->curlen += n; + in += n; + inlen -= n; + + if(md->curlen == block_size) + { + sha_compress(md, md->buf); + md->length += 8*block_size; + md->curlen = 0; + } + } + } +} + +static void sha_done(sha256_state* md, void* out) +{ + int i; + + // Increase the length of the message + md->length += md->curlen * 8; + + // Append the '1' bit + md->buf[md->curlen++] = (unsigned char)0x80; + + // If the length is currently above 56 bytes we append zeros then compress. + // Then we can fall back to padding zeros and length encoding like normal. + if(md->curlen > 56) + { + while(md->curlen < 64) + md->buf[md->curlen++] = 0; + sha_compress(md, md->buf); + md->curlen = 0; + } + + // Pad up to 56 bytes of zeroes + while(md->curlen < 56) + md->buf[md->curlen++] = 0; + + // Store length + store64(md->length, md->buf+56); + sha_compress(md, md->buf); + + // Copy output + for(i = 0; i < 8; i++) + store32(md->state[i], (unsigned char *)out+(4*i)); +} + +void sha256_init(SHA256_CTX *ctxt) +{ + sha_init(ctxt); +} + +void sha256_update(SHA256_CTX *ctxt, const void *data, size_t data_len) +{ + sha_process(ctxt, data, data_len); +} + +SHA256_DIGEST sha256_finish(SHA256_CTX *ctxt) +{ + SHA256_DIGEST result; + sha_done(ctxt, result.data); + return result; +} + +#endif diff --git a/src/base/hash_openssl.c b/src/base/hash_openssl.c new file mode 100644 index 000000000..4f500ae20 --- /dev/null +++ b/src/base/hash_openssl.c @@ -0,0 +1,39 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#if defined(CONF_OPENSSL) +#include "hash_ctxt.h" + +void sha256_init(SHA256_CTX *ctxt) +{ + SHA256_Init(ctxt); +} + +void sha256_update(SHA256_CTX *ctxt, const void *data, size_t data_len) +{ + SHA256_Update(ctxt, data, data_len); +} + +SHA256_DIGEST sha256_finish(SHA256_CTX *ctxt) +{ + SHA256_DIGEST result; + SHA256_Final(result.data, ctxt); + return result; +} + +void md5_init(MD5_CTX *ctxt) +{ + MD5_Init(ctxt); +} + +void md5_update(MD5_CTX *ctxt, const void *data, size_t data_len) +{ + MD5_Update(ctxt, data, data_len); +} + +MD5_DIGEST md5_finish(MD5_CTX *ctxt) +{ + MD5_DIGEST result; + MD5_Final(result.data, ctxt); + return result; +} +#endif diff --git a/src/base/math.h b/src/base/math.h new file mode 100644 index 000000000..d108570db --- /dev/null +++ b/src/base/math.h @@ -0,0 +1,89 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_MATH_H +#define BASE_MATH_H + +#include + +template +inline T clamp(T val, T min, T max) +{ + if(val < min) + return min; + if(val > max) + return max; + return val; +} + +inline float sign(float f) +{ + return f<0.0f?-1.0f:1.0f; +} + +inline int round_to_int(float f) +{ + if(f > 0) + return (int)(f+0.5f); + return (int)(f-0.5f); +} + +template +inline T mix(const T a, const T b, TB amount) +{ + return a + (b-a)*amount; +} + +template +inline T bezier(const T p0, const T p1, const T p2, const T p3, TB amount) +{ + // De-Casteljau Algorithm + const T c10 = mix(p0, p1, amount); + const T c11 = mix(p1, p2, amount); + const T c12 = mix(p2, p3, amount); + + const T c20 = mix(c10, c11, amount); + const T c21 = mix(c11, c12, amount); + + return mix(c20, c21, amount); // c30 +} + +inline int random_int() { return (((rand() & 0xffff) << 16) | (rand() & 0xffff)) & 0x7FFFFFFF; } +inline float random_float() { return rand()/(float)(RAND_MAX); } + +// float to fixed +inline int f2fx(float v) { return (int)(v*(float)(1<<10)); } +inline float fx2f(int v) { return v*(1.0f/(1<<10)); } + +// int to fixed +inline int i2fx(int v) { return v<<10; } +inline int fx2i(int v) { return v>>10; } + +inline int gcd(int a, int b) +{ + while(b != 0) + { + int c = a % b; + a = b; + b = c; + } + return a; +} + +class fxp +{ + int value; +public: + void set(int v) { value = v; } + int get() const { return value; } + fxp &operator = (int v) { value = v<<10; return *this; } + fxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; } + operator float() const { return value/(float)(1<<10); } +}; + +const float pi = 3.1415926535897932384626433f; + +template inline T minimum(T a, T b) { return a inline T maximum(T a, T b) { return a>b?a:b; } +template inline T absolute(T a) { return a +#include +#include +#include +#include +#include + +#include "system.h" + +#include +#include + +#if defined(CONF_FAMILY_UNIX) + #include + #include + + /* unix net includes */ + #include + #include + #include + #include + #include + #include + #include + #include + + #include + + #if defined(CONF_PLATFORM_MACOSX) + #include + #endif + +#elif defined(CONF_FAMILY_WINDOWS) + #define WIN32_LEAN_AND_MEAN + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#else + #error NOT IMPLEMENTED +#endif + +#if defined(CONF_ARCH_IA32) || defined(CONF_ARCH_AMD64) + #include //_mm_pause +#endif + +#if defined(CONF_PLATFORM_SOLARIS) + #include +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +IOHANDLE io_stdin() { return (IOHANDLE)stdin; } +IOHANDLE io_stdout() { return (IOHANDLE)stdout; } +IOHANDLE io_stderr() { return (IOHANDLE)stderr; } + +static DBG_LOGGER loggers[16]; +static int num_loggers = 0; + +static NETSTATS network_stats = {0}; + +static NETSOCKET invalid_socket = {NETTYPE_INVALID, -1, -1}; + +void dbg_logger(DBG_LOGGER logger) +{ + loggers[num_loggers++] = logger; +} + +void dbg_assert_imp(const char *filename, int line, int test, const char *msg) +{ + if(!test) + { + dbg_msg("assert", "%s(%d): %s", filename, line, msg); + dbg_break(); + } +} + +void dbg_break() +{ + *((volatile unsigned*)0) = 0x0; +} + +void dbg_msg(const char *sys, const char *fmt, ...) +{ + va_list args; + char str[1024*4]; + char *msg; + int i, len; + + char timestr[80]; + str_timestamp_format(timestr, sizeof(timestr), FORMAT_SPACE); + + str_format(str, sizeof(str), "[%s][%s]: ", timestr, sys); + + len = str_length(str); + msg = (char *)str + len; + + va_start(args, fmt); +#if defined(CONF_FAMILY_WINDOWS) && !defined(__GNUC__) + _vsprintf_p(msg, sizeof(str)-len, fmt, args); +#else + vsnprintf(msg, sizeof(str)-len, fmt, args); +#endif + va_end(args); + + for(i = 0; i < num_loggers; i++) + loggers[i](str); +} + +#if defined(CONF_FAMILY_WINDOWS) +static void logger_win_console(const char *line) +{ + #define _MAX_LENGTH 1024 + #define _MAX_LENGTH_ERROR (_MAX_LENGTH+32) + + static const int UNICODE_REPLACEMENT_CHAR = 0xfffd; + + static const char *STR_TOO_LONG = "(str too long)"; + static const char *INVALID_UTF8 = "(invalid utf8)"; + + wchar_t wline[_MAX_LENGTH_ERROR]; + size_t len = 0; + + const char *read = line; + const char *error = STR_TOO_LONG; + while(len < _MAX_LENGTH) + { + // Read a character. This also advances the read pointer + int glyph = str_utf8_decode(&read); + if(glyph < 0) + { + // If there was an error decoding the UTF-8 sequence, + // emit a replacement character. Since the + // str_utf8_decode function will not work after such + // an error, end the string here. + glyph = UNICODE_REPLACEMENT_CHAR; + error = INVALID_UTF8; + wline[len] = glyph; + break; + } + else if(glyph == 0) + { + // A character code of 0 signals the end of the string. + error = 0; + break; + } + else if(glyph > 0xffff) + { + // Since the windows console does not really support + // UTF-16, don't mind doing actual UTF-16 encoding, + // but rather emit a replacement character. + glyph = UNICODE_REPLACEMENT_CHAR; + } + else if(glyph == 0x2022) + { + // The 'bullet' character might get converted to a 'beep', + // so it will be replaced by the 'bullet operator'. + glyph = 0x2219; + } + + // Again, since the windows console does not really support + // UTF-16, but rather something along the lines of UCS-2, + // simply put the character into the output. + wline[len++] = glyph; + } + + if(error) + { + read = error; + while(1) + { + // Errors are simple ascii, no need for UTF-8 + // decoding + char character = *read; + if(character == 0) + break; + + dbg_assert(len < _MAX_LENGTH_ERROR, "str too short for error"); + wline[len++] = character; + read++; + } + } + + // Terminate the line + dbg_assert(len < _MAX_LENGTH_ERROR, "str too short for \\r"); + wline[len++] = '\r'; + dbg_assert(len < _MAX_LENGTH_ERROR, "str too short for \\n"); + wline[len++] = '\n'; + + // Ignore any error that might occur + WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), wline, len, 0, 0); + + #undef _MAX_LENGTH + #undef _MAX_LENGTH_ERROR +} +#endif + +static void logger_stdout(const char *line) +{ + printf("%s\n", line); + fflush(stdout); +} + +#if defined(CONF_FAMILY_WINDOWS) +static void logger_win_debugger(const char *line) +{ + WCHAR wBuffer[512]; + MultiByteToWideChar(CP_UTF8, 0, line, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + OutputDebugStringW(wBuffer); + OutputDebugStringW(L"\n"); +} +#endif + +static IOHANDLE logfile = 0; +static void logger_file(const char *line) +{ + io_write(logfile, line, str_length(line)); + io_write_newline(logfile); + io_flush(logfile); +} + +void dbg_logger_stdout() +{ +#if defined(CONF_FAMILY_WINDOWS) + if(GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) == FILE_TYPE_CHAR) + { + dbg_logger(logger_win_console); + return; + } +#endif + dbg_logger(logger_stdout); +} + +void dbg_logger_debugger() +{ +#if defined(CONF_FAMILY_WINDOWS) + dbg_logger(logger_win_debugger); +#endif +} + +void dbg_logger_file(const char *filename) +{ + IOHANDLE handle = io_open(filename, IOFLAG_WRITE); + if(handle) + dbg_logger_filehandle(handle); + else + dbg_msg("dbg/logger", "failed to open '%s' for logging", filename); +} + +void dbg_logger_filehandle(IOHANDLE handle) +{ + logfile = handle; + if(logfile) + dbg_logger(logger_file); +} + +#if defined(CONF_FAMILY_WINDOWS) +static DWORD old_console_mode; + +void dbg_console_init() +{ + HANDLE handle; + DWORD console_mode; + + handle = GetStdHandle(STD_INPUT_HANDLE); + GetConsoleMode(handle, &old_console_mode); + console_mode = old_console_mode & (~ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS); + SetConsoleMode(handle, console_mode); +} +void dbg_console_cleanup() +{ + SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), old_console_mode); +} +#endif +/* */ + +void *mem_alloc(unsigned size) +{ + return malloc(size); +} + +void mem_free(void *p) +{ + free(p); +} + +void mem_copy(void *dest, const void *source, unsigned size) +{ + memcpy(dest, source, size); +} + +void mem_move(void *dest, const void *source, unsigned size) +{ + memmove(dest, source, size); +} + +void mem_zero(void *block,unsigned size) +{ + memset(block, 0, size); +} + +IOHANDLE io_open_impl(const char *filename, int flags) +{ + dbg_assert(flags == (IOFLAG_READ | IOFLAG_SKIP_BOM) || flags == IOFLAG_READ || flags == IOFLAG_WRITE || flags == IOFLAG_APPEND, "flags must be read, read+skipbom, write or append"); +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + if((flags & IOFLAG_READ) != 0) + { + // check for filename case sensitive + WIN32_FIND_DATAW finddata; + HANDLE handle; + char buffer[IO_MAX_PATH_LENGTH]; + + int length = str_length(filename); + if(!filename || !length || filename[length-1] == '\\') + return 0x0; + MultiByteToWideChar(CP_UTF8, 0, filename, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + handle = FindFirstFileW(wBuffer, &finddata); + if(handle == INVALID_HANDLE_VALUE) + return 0x0; + WideCharToMultiByte(CP_UTF8, 0, finddata.cFileName, -1, buffer, sizeof(buffer), NULL, NULL); + if(str_comp(filename+length-str_length(buffer), buffer) != 0) + { + FindClose(handle); + return 0x0; + } + FindClose(handle); + return (IOHANDLE)_wfsopen(wBuffer, L"rb", _SH_DENYNO); + } + if(flags == IOFLAG_WRITE) + { + MultiByteToWideChar(CP_UTF8, 0, filename, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + return (IOHANDLE)_wfsopen(wBuffer, L"wb", _SH_DENYNO); + } + if(flags == IOFLAG_APPEND) + { + MultiByteToWideChar(CP_UTF8, 0, filename, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + return (IOHANDLE)_wfsopen(wBuffer, L"ab", _SH_DENYNO); + } + return 0x0; +#else + if((flags & IOFLAG_READ) != 0) + return (IOHANDLE)fopen(filename, "rb"); + if(flags == IOFLAG_WRITE) + return (IOHANDLE)fopen(filename, "wb"); + if(flags == IOFLAG_APPEND) + return (IOHANDLE)fopen(filename, "ab"); + return 0x0; +#endif +} + +IOHANDLE io_open(const char *filename, int flags) +{ + IOHANDLE result = io_open_impl(filename, flags); + unsigned char buf[3]; + if((flags & IOFLAG_SKIP_BOM) == 0 || !result) + { + return result; + } + if(io_read(result, buf, sizeof(buf)) != 3 || buf[0] != 0xef || buf[1] != 0xbb || buf[2] != 0xbf) + { + io_seek(result, 0, IOSEEK_START); + } + return result; +} + +unsigned io_read(IOHANDLE io, void *buffer, unsigned size) +{ + return fread(buffer, 1, size, (FILE*)io); +} + +void io_read_all(IOHANDLE io, void **result, unsigned *result_len) +{ + unsigned char *buffer = malloc(1024); + unsigned len = 0; + unsigned cap = 1024; + unsigned read; + + *result = 0; + *result_len = 0; + + while((read = io_read(io, buffer + len, cap - len)) != 0) + { + len += read; + if(len == cap) + { + cap *= 2; + buffer = realloc(buffer, cap); + } + } + if(len == cap) + { + buffer = realloc(buffer, cap + 1); + } + // ensure null termination + buffer[len] = 0; + *result = buffer; + *result_len = len; +} + +char *io_read_all_str(IOHANDLE io) +{ + void *buffer; + unsigned len; + + io_read_all(io, &buffer, &len); + if(mem_has_null(buffer, len)) + { + free(buffer); + return 0; + } + return buffer; +} + +unsigned io_unread_byte(IOHANDLE io, unsigned char byte) +{ + return ungetc(byte, (FILE*)io) == EOF; +} + +unsigned io_skip(IOHANDLE io, int size) +{ + fseek((FILE*)io, size, SEEK_CUR); + return size; +} + +int io_seek(IOHANDLE io, int offset, int origin) +{ + int real_origin; + + switch(origin) + { + case IOSEEK_START: + real_origin = SEEK_SET; + break; + case IOSEEK_CUR: + real_origin = SEEK_CUR; + break; + case IOSEEK_END: + real_origin = SEEK_END; + break; + default: + return -1; + } + + return fseek((FILE*)io, offset, real_origin); +} + +long int io_tell(IOHANDLE io) +{ + return ftell((FILE*)io); +} + +long int io_length(IOHANDLE io) +{ + long int length; + io_seek(io, 0, IOSEEK_END); + length = io_tell(io); + io_seek(io, 0, IOSEEK_START); + return length; +} + +unsigned io_write(IOHANDLE io, const void *buffer, unsigned size) +{ + return fwrite(buffer, 1, size, (FILE*)io); +} + +unsigned io_write_newline(IOHANDLE io) +{ +#if defined(CONF_FAMILY_WINDOWS) + return fwrite("\r\n", 1, 2, (FILE*)io); +#else + return fwrite("\n", 1, 1, (FILE*)io); +#endif +} + +int io_close(IOHANDLE io) +{ + fclose((FILE*)io); + return 0; +} + +int io_flush(IOHANDLE io) +{ + fflush((FILE*)io); + return 0; +} + +struct THREAD_RUN +{ + void (*threadfunc)(void *); + void *u; +}; + +#if defined(CONF_FAMILY_UNIX) +static void *thread_run(void *user) +#elif defined(CONF_FAMILY_WINDOWS) +static unsigned long __stdcall thread_run(void *user) +#else +#error not implemented +#endif +{ + struct THREAD_RUN *data = user; + void (*threadfunc)(void *) = data->threadfunc; + void *u = data->u; + free(data); + threadfunc(u); + return 0; +} + +void *thread_init(void (*threadfunc)(void *), void *u) +{ + struct THREAD_RUN *data = malloc(sizeof(*data)); + data->threadfunc = threadfunc; + data->u = u; +#if defined(CONF_FAMILY_UNIX) + { + pthread_t id; + pthread_attr_t attr; + pthread_attr_init(&attr); +#if defined(CONF_PLATFORM_MACOS) + pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INTERACTIVE, 0); +#endif + if(pthread_create(&id, &attr, thread_run, data) != 0) + { + return 0; + } + return (void*)id; + } +#elif defined(CONF_FAMILY_WINDOWS) + return CreateThread(NULL, 0, thread_run, data, 0, NULL); +#else + #error not implemented +#endif +} + +void thread_wait(void *thread) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_join((pthread_t)thread, NULL); +#elif defined(CONF_FAMILY_WINDOWS) + WaitForSingleObject((HANDLE)thread, INFINITE); +#else + #error not implemented +#endif +} + +void thread_destroy(void *thread) +{ +#if defined(CONF_FAMILY_WINDOWS) + CloseHandle((HANDLE)thread); +#endif +} + +void thread_yield() +{ +#if defined(CONF_FAMILY_UNIX) + sched_yield(); +#elif defined(CONF_FAMILY_WINDOWS) + Sleep(0); +#else + #error not implemented +#endif +} + +void thread_sleep(int milliseconds) +{ +#if defined(CONF_FAMILY_UNIX) + usleep(milliseconds*1000); +#elif defined(CONF_FAMILY_WINDOWS) + Sleep(milliseconds); +#else + #error not implemented +#endif +} + +void thread_detach(void *thread) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_detach((pthread_t)(thread)); +#elif defined(CONF_FAMILY_WINDOWS) + CloseHandle(thread); +#else + #error not implemented +#endif +} + +void cpu_relax() +{ +#if defined(CONF_ARCH_IA32) || defined(CONF_ARCH_AMD64) + _mm_pause(); +#else + (void) 0; +#endif +} + + + +#if defined(CONF_FAMILY_UNIX) +typedef pthread_mutex_t LOCKINTERNAL; +#elif defined(CONF_FAMILY_WINDOWS) +typedef CRITICAL_SECTION LOCKINTERNAL; +#else + #error not implemented on this platform +#endif + +LOCK lock_create() +{ + LOCKINTERNAL *lock = (LOCKINTERNAL*)mem_alloc(sizeof(LOCKINTERNAL)); + +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_init(lock, 0x0); +#elif defined(CONF_FAMILY_WINDOWS) + InitializeCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif + return (LOCK)lock; +} + +void lock_destroy(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_destroy((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + DeleteCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif + mem_free(lock); +} + +int lock_trylock(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + return pthread_mutex_trylock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + return !TryEnterCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +void lock_wait(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_lock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + EnterCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +void lock_unlock(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_unlock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + LeaveCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +#if !defined(CONF_PLATFORM_MACOSX) + #if defined(CONF_FAMILY_UNIX) + void semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); } + void semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); } + void semaphore_signal(SEMAPHORE *sem) { sem_post(sem); } + void semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); } + #elif defined(CONF_FAMILY_WINDOWS) + void semaphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); } + void semaphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, INFINITE); } + void semaphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); } + void semaphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); } + #else + #error not implemented on this platform + #endif +#endif + + +/* ----- time ----- */ +int64 time_get() +{ +#if defined(CONF_FAMILY_UNIX) + struct timeval val; + gettimeofday(&val, NULL); + return (int64)val.tv_sec*(int64)1000000+(int64)val.tv_usec; +#elif defined(CONF_FAMILY_WINDOWS) + static int64 last = 0; + int64 t; + QueryPerformanceCounter((PLARGE_INTEGER)&t); + if(ttype != NETTYPE_IPV4) + { + dbg_msg("system", "couldn't convert NETADDR of type %d to ipv4", src->type); + return; + } + + dest->sin_family = AF_INET; + dest->sin_port = htons(src->port); + mem_copy(&dest->sin_addr.s_addr, src->ip, 4); +} + +static void netaddr_to_sockaddr_in6(const NETADDR *src, struct sockaddr_in6 *dest) +{ + mem_zero(dest, sizeof(struct sockaddr_in6)); + if(src->type != NETTYPE_IPV6) + { + dbg_msg("system", "couldn't not convert NETADDR of type %d to ipv6", src->type); + return; + } + + dest->sin6_family = AF_INET6; + dest->sin6_port = htons(src->port); + mem_copy(&dest->sin6_addr.s6_addr, src->ip, 16); +} + +static void sockaddr_to_netaddr(const struct sockaddr *src, NETADDR *dst) +{ + if(src->sa_family == AF_INET) + { + mem_zero(dst, sizeof(NETADDR)); + dst->type = NETTYPE_IPV4; + dst->port = htons(((struct sockaddr_in*)src)->sin_port); + mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); + } + else if(src->sa_family == AF_INET6) + { + mem_zero(dst, sizeof(NETADDR)); + dst->type = NETTYPE_IPV6; + dst->port = htons(((struct sockaddr_in6*)src)->sin6_port); + mem_copy(dst->ip, &((struct sockaddr_in6*)src)->sin6_addr.s6_addr, 16); + } + else + { + mem_zero(dst, sizeof(struct sockaddr)); + dbg_msg("system", "couldn't convert sockaddr of family %d", src->sa_family); + } +} + +int net_addr_comp(const NETADDR *a, const NETADDR *b, int check_port) +{ + if(a->type == b->type && mem_comp(a->ip, b->ip, a->type == NETTYPE_IPV4 ? NETADDR_SIZE_IPV4 : NETADDR_SIZE_IPV6) == 0 && (!check_port || a->port == b->port)) + return 0; + return -1; +} + +void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port) +{ + if(addr->type == NETTYPE_IPV4) + { + if(add_port != 0) + str_format(string, max_length, "%d.%d.%d.%d:%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3], addr->port); + else + str_format(string, max_length, "%d.%d.%d.%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3]); + } + else if(addr->type == NETTYPE_IPV6) + { + if(add_port != 0) + str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", + (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], + (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15], + addr->port); + else + str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]", + (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], + (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15]); + } + else + str_format(string, max_length, "unknown type %d", addr->type); +} + +static int priv_net_extract(const char *hostname, char *host, int max_host, int *port) +{ + int i; + + *port = 0; + host[0] = 0; + + if(hostname[0] == '[') + { + // ipv6 mode + for(i = 1; i < max_host && hostname[i] && hostname[i] != ']'; i++) + host[i-1] = hostname[i]; + host[i-1] = 0; + if(hostname[i] != ']') // malformatted + return -1; + + i++; + if(hostname[i] == ':') + *port = atol(hostname+i+1); + } + else + { + // generic mode (ipv4, hostname etc) + for(i = 0; i < max_host-1 && hostname[i] && hostname[i] != ':'; i++) + host[i] = hostname[i]; + host[i] = 0; + + if(hostname[i] == ':') + *port = atol(hostname+i+1); + } + + return 0; +} + +int net_host_lookup(const char *hostname, NETADDR *addr, int types) +{ + struct addrinfo hints; + struct addrinfo *result; + int e; + char host[256]; + int port = 0; + + if(priv_net_extract(hostname, host, sizeof(host), &port)) + return -1; + /* + dbg_msg("host lookup", "host='%s' port=%d %d", host, port, types); + */ + + mem_zero(&hints, sizeof(hints)); + + hints.ai_family = AF_UNSPEC; + + if(types == NETTYPE_IPV4) + hints.ai_family = AF_INET; + else if(types == NETTYPE_IPV6) + hints.ai_family = AF_INET6; + + e = getaddrinfo(host, NULL, &hints, &result); + if(e != 0 || !result) + return -1; + + sockaddr_to_netaddr(result->ai_addr, addr); + freeaddrinfo(result); + addr->port = port; + return 0; +} + +static int parse_int(int *out, const char **str) +{ + int i = 0; + *out = 0; + if(**str < '0' || **str > '9') + return -1; + + i = **str - '0'; + (*str)++; + + while(1) + { + if(**str < '0' || **str > '9') + { + *out = i; + return 0; + } + + i = (i*10) + (**str - '0'); + (*str)++; + } + + return 0; +} + +static int parse_char(char c, const char **str) +{ + if(**str != c) return -1; + (*str)++; + return 0; +} + +static int parse_uint8(unsigned char *out, const char **str) +{ + int i; + if(parse_int(&i, str) != 0) return -1; + if(i < 0 || i > 0xff) return -1; + *out = i; + return 0; +} + +static int parse_uint16(unsigned short *out, const char **str) +{ + int i; + if(parse_int(&i, str) != 0) return -1; + if(i < 0 || i > 0xffff) return -1; + *out = i; + return 0; +} + +int net_addr_from_str(NETADDR *addr, const char *string) +{ + const char *str = string; + mem_zero(addr, sizeof(NETADDR)); + + if(str[0] == '[') + { + /* ipv6 */ + struct sockaddr_in6 sa6; + char buf[128]; + int i; + str++; + for(i = 0; i < 127 && str[i] && str[i] != ']'; i++) + buf[i] = str[i]; + buf[i] = 0; + str += i; +#if defined(CONF_FAMILY_WINDOWS) + { + int size; + sa6.sin6_family = AF_INET6; + size = (int)sizeof(sa6); + if(WSAStringToAddressA(buf, AF_INET6, NULL, (struct sockaddr *)&sa6, &size) != 0) + return -1; + } +#else + sa6.sin6_family = AF_INET6; + + if(inet_pton(AF_INET6, buf, &sa6.sin6_addr) != 1) + return -1; +#endif + sockaddr_to_netaddr((struct sockaddr *)&sa6, addr); + + if(*str == ']') + { + str++; + if(*str == ':') + { + str++; + if(parse_uint16(&addr->port, &str)) + return -1; + } + } + else + return -1; + + return 0; + } + else + { + /* ipv4 */ + if(parse_uint8(&addr->ip[0], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[1], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[2], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[3], &str)) return -1; + if(*str == ':') + { + str++; + if(parse_uint16(&addr->port, &str)) return -1; + } + + addr->type = NETTYPE_IPV4; + } + + return 0; +} + +static void priv_net_close_socket(int sock) +{ +#if defined(CONF_FAMILY_WINDOWS) + closesocket(sock); +#else + close(sock); +#endif +} + +static int priv_net_close_all_sockets(NETSOCKET sock) +{ + /* close down ipv4 */ + if(sock.ipv4sock >= 0) + { + priv_net_close_socket(sock.ipv4sock); + sock.ipv4sock = -1; + sock.type &= ~NETTYPE_IPV4; + } + + /* close down ipv6 */ + if(sock.ipv6sock >= 0) + { + priv_net_close_socket(sock.ipv6sock); + sock.ipv6sock = -1; + sock.type &= ~NETTYPE_IPV6; + } + return 0; +} + +static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, int sockaddrlen, int use_random_port) +{ + int sock, e; + + /* create socket */ + sock = socket(domain, type, 0); + if(sock < 0) + { +#if defined(CONF_FAMILY_WINDOWS) + char buf[128]; + WCHAR wBuffer[128]; + int error = WSAGetLastError(); + if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, wBuffer, sizeof(wBuffer) / sizeof(WCHAR), 0) == 0) + wBuffer[0] = 0; + WideCharToMultiByte(CP_UTF8, 0, wBuffer, -1, buf, sizeof(buf), NULL, NULL); + dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, error, buf); +#else + dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); +#endif + return -1; + } + + /* set to IPv6 only if thats what we are creating */ +#if defined(IPV6_V6ONLY) /* windows sdk 6.1 and higher */ + if(domain == AF_INET6) + { + int ipv6only = 1; + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6only, sizeof(ipv6only)); + } +#endif + + /* bind the socket */ + while(1) + { + /* pick random port */ + if(use_random_port) + { + int port = htons(rand()%16384+49152); /* 49152 to 65535 */ + if(domain == AF_INET) + ((struct sockaddr_in *)(addr))->sin_port = port; + else + ((struct sockaddr_in6 *)(addr))->sin6_port = port; + } + + e = bind(sock, addr, sockaddrlen); + if(e == 0) + break; + else + { +#if defined(CONF_FAMILY_WINDOWS) + char buf[128]; + WCHAR wBuffer[128]; + int error = WSAGetLastError(); + if(error == WSAEADDRINUSE && use_random_port) + continue; + if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, wBuffer, sizeof(wBuffer) / sizeof(WCHAR), 0) == 0) + wBuffer[0] = 0; + WideCharToMultiByte(CP_UTF8, 0, wBuffer, -1, buf, sizeof(buf), NULL, NULL); + dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, error, buf); +#else + if(errno == EADDRINUSE && use_random_port) + continue; + dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); +#endif + priv_net_close_socket(sock); + return -1; + } + } + + /* return the newly created socket */ + return sock; +} + +NETSOCKET net_udp_create(NETADDR bindaddr, int use_random_port) +{ + NETSOCKET sock = invalid_socket; + NETADDR tmpbindaddr = bindaddr; + int broadcast = 1; + int recvsize = 65536; + + if(bindaddr.type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV4; + netaddr_to_sockaddr_in(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr), use_random_port); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV4; + sock.ipv4sock = socket; + + /* set broadcast */ + setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); + + /* set receive buffer size */ + setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); + } + } + + if(bindaddr.type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV6; + netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET6, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr), use_random_port); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV6; + sock.ipv6sock = socket; + + /* set broadcast */ + setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); + + /* set receive buffer size */ + setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); + } + } + + /* set non-blocking */ + net_set_non_blocking(sock); + + /* return */ + return sock; +} + +int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size) +{ + int d = -1; + + if(addr->type&NETTYPE_IPV4) + { + if(sock.ipv4sock >= 0) + { + struct sockaddr_in sa; + if(addr->type&NETTYPE_LINK_BROADCAST) + { + mem_zero(&sa, sizeof(sa)); + sa.sin_port = htons(addr->port); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = INADDR_BROADCAST; + } + else + netaddr_to_sockaddr_in(addr, &sa); + + d = sendto((int)sock.ipv4sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + } + else + dbg_msg("net", "can't send ipv4 traffic to this socket"); + } + + if(addr->type&NETTYPE_IPV6) + { + if(sock.ipv6sock >= 0) + { + struct sockaddr_in6 sa; + if(addr->type&NETTYPE_LINK_BROADCAST) + { + mem_zero(&sa, sizeof(sa)); + sa.sin6_port = htons(addr->port); + sa.sin6_family = AF_INET6; + sa.sin6_addr.s6_addr[0] = 0xff; /* multicast */ + sa.sin6_addr.s6_addr[1] = 0x02; /* link local scope */ + sa.sin6_addr.s6_addr[15] = 1; /* all nodes */ + } + else + netaddr_to_sockaddr_in6(addr, &sa); + + d = sendto((int)sock.ipv6sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + } + else + dbg_msg("net", "can't send ipv6 traffic to this socket"); + } + /* + else + dbg_msg("net", "can't send to network of type %d", addr->type); + */ + + /*if(d < 0) + { + char addrstr[256]; + net_addr_str(addr, addrstr, sizeof(addrstr)); + + dbg_msg("net", "sendto error (%d '%s')", errno, strerror(errno)); + dbg_msg("net", "\tsock = %d %x", sock, sock); + dbg_msg("net", "\tsize = %d %x", size, size); + dbg_msg("net", "\taddr = %s", addrstr); + + }*/ + network_stats.sent_bytes += size; + network_stats.sent_packets++; + return d; +} + +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize) +{ + char sockaddrbuf[128]; + socklen_t fromlen;// = sizeof(sockaddrbuf); + int bytes = 0; + + if(sock.ipv4sock >= 0) + { + fromlen = sizeof(struct sockaddr_in); + bytes = recvfrom(sock.ipv4sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + } + + if(bytes <= 0 && sock.ipv6sock >= 0) + { + fromlen = sizeof(struct sockaddr_in6); + bytes = recvfrom(sock.ipv6sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + } + + if(bytes > 0) + { + sockaddr_to_netaddr((struct sockaddr *)&sockaddrbuf, addr); + network_stats.recv_bytes += bytes; + network_stats.recv_packets++; + return bytes; + } + else if(bytes == 0) + return 0; + return -1; /* error */ +} + +int net_udp_close(NETSOCKET sock) +{ + return priv_net_close_all_sockets(sock); +} + +NETSOCKET net_tcp_create(NETADDR bindaddr) +{ + NETSOCKET sock = invalid_socket; + NETADDR tmpbindaddr = bindaddr; + + if(bindaddr.type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV4; + netaddr_to_sockaddr_in(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), 0); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV4; + sock.ipv4sock = socket; + } + } + + if(bindaddr.type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV6; + netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET6, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), 0); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV6; + sock.ipv6sock = socket; + } + } + + /* return */ + return sock; +} + +int net_tcp_set_linger(NETSOCKET sock, int state) +{ + struct linger linger_state; + linger_state.l_onoff = state; + linger_state.l_linger = 0; + + if(sock.ipv4sock >= 0) + { + /* set linger */ + setsockopt(sock.ipv4sock, SOL_SOCKET, SO_LINGER, (const char*)&linger_state, sizeof(linger_state)); + } + + if(sock.ipv6sock >= 0) + { + /* set linger */ + setsockopt(sock.ipv6sock, SOL_SOCKET, SO_LINGER, (const char*)&linger_state, sizeof(linger_state)); + } + + return 0; +} + +int net_set_non_blocking(NETSOCKET sock) +{ + unsigned long mode = 1; + if(sock.ipv4sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + if(sock.ipv6sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + return 0; +} + +int net_set_blocking(NETSOCKET sock) +{ + unsigned long mode = 0; + if(sock.ipv4sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + if(sock.ipv6sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + return 0; +} + +int net_tcp_listen(NETSOCKET sock, int backlog) +{ + int err = -1; + if(sock.ipv4sock >= 0) + err = listen(sock.ipv4sock, backlog); + if(sock.ipv6sock >= 0) + err = listen(sock.ipv6sock, backlog); + return err; +} + +int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) +{ + int s; + socklen_t sockaddr_len; + + *new_sock = invalid_socket; + + if(sock.ipv4sock >= 0) + { + struct sockaddr_in addr; + sockaddr_len = sizeof(addr); + + s = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len); + + if (s != -1) + { + sockaddr_to_netaddr((const struct sockaddr *)&addr, a); + new_sock->type = NETTYPE_IPV4; + new_sock->ipv4sock = s; + return s; + } + } + + if(sock.ipv6sock >= 0) + { + struct sockaddr_in6 addr; + sockaddr_len = sizeof(addr); + + s = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len); + + if (s != -1) + { + sockaddr_to_netaddr((const struct sockaddr *)&addr, a); + new_sock->type = NETTYPE_IPV6; + new_sock->ipv6sock = s; + return s; + } + } + + return -1; +} + +int net_tcp_connect(NETSOCKET sock, const NETADDR *a) +{ + if(a->type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + netaddr_to_sockaddr_in(a, &addr); + return connect(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr)); + } + + if(a->type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + netaddr_to_sockaddr_in6(a, &addr); + return connect(sock.ipv6sock, (struct sockaddr *)&addr, sizeof(addr)); + } + + return -1; +} + +int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr) +{ + int res = 0; + + net_set_non_blocking(sock); + res = net_tcp_connect(sock, &bindaddr); + net_set_blocking(sock); + + return res; +} + +int net_tcp_send(NETSOCKET sock, const void *data, int size) +{ + int bytes = -1; + + if(sock.ipv4sock >= 0) + bytes = send((int)sock.ipv4sock, (const char*)data, size, 0); + if(sock.ipv6sock >= 0) + bytes = send((int)sock.ipv6sock, (const char*)data, size, 0); + + return bytes; +} + +int net_tcp_recv(NETSOCKET sock, void *data, int maxsize) +{ + int bytes = -1; + + if(sock.ipv4sock >= 0) + bytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0); + if(sock.ipv6sock >= 0) + bytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0); + + return bytes; +} + +int net_tcp_close(NETSOCKET sock) +{ + return priv_net_close_all_sockets(sock); +} + +int net_errno() +{ +#if defined(CONF_FAMILY_WINDOWS) + return WSAGetLastError(); +#else + return errno; +#endif +} + +int net_would_block() +{ +#if defined(CONF_FAMILY_WINDOWS) + return net_errno() == WSAEWOULDBLOCK; +#else + return net_errno() == EWOULDBLOCK; +#endif +} + +void net_invalidate_socket(NETSOCKET *socket) +{ + *socket = invalid_socket; +} + +int net_init() +{ +#if defined(CONF_FAMILY_WINDOWS) + WSADATA wsaData; + int err = WSAStartup(MAKEWORD(1, 1), &wsaData); + dbg_assert(err == 0, "network initialization failed."); + return err==0?0:1; +#endif + + return 0; +} + +#if defined (CONF_FAMILY_WINDOWS) +static inline time_t filetime_to_unixtime(LPFILETIME filetime) +{ + time_t t; + ULARGE_INTEGER li; + li.LowPart = filetime->dwLowDateTime; + li.HighPart = filetime->dwHighDateTime; + + li.QuadPart /= 10000000; // 100ns to 1s + li.QuadPart -= 11644473600LL; // Windows epoch is in the past + + t = li.QuadPart; + return t == li.QuadPart ? t : (time_t)-1; +} +#endif + +void fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) +{ +#if defined(CONF_FAMILY_WINDOWS) + WIN32_FIND_DATAW finddata; + HANDLE handle; + char buffer[IO_MAX_PATH_LENGTH]; + char buffer2[IO_MAX_PATH_LENGTH]; + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + int length; + + str_format(buffer, sizeof(buffer), "%s/*", dir); + MultiByteToWideChar(CP_UTF8, 0, buffer, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + + handle = FindFirstFileW(wBuffer, &finddata); + if(handle == INVALID_HANDLE_VALUE) + return; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + /* add all the entries */ + do + { + WideCharToMultiByte(CP_UTF8, 0, finddata.cFileName, -1, buffer2, sizeof(buffer2), NULL, NULL); + str_copy(buffer+length, buffer2, (int)sizeof(buffer)-length); + if(cb(buffer2, (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0, type, user)) + break; + } + while(FindNextFileW(handle, &finddata)); + + FindClose(handle); +#else + struct dirent *entry; + char buffer[IO_MAX_PATH_LENGTH]; + int length; + DIR *d = opendir(dir); + + if(!d) + return; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + while((entry = readdir(d)) != NULL) + { + str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + if(cb(entry->d_name, entry->d_type == DT_UNKNOWN ? fs_is_dir(buffer) : entry->d_type == DT_DIR, type, user)) + break; + } + + /* close the directory and return */ + closedir(d); +#endif +} + +void fs_listdir_fileinfo(const char *dir, FS_LISTDIR_CALLBACK_FILEINFO cb, int type, void *user) +{ +#if defined(CONF_FAMILY_WINDOWS) + WIN32_FIND_DATAW finddata; + HANDLE handle; + char buffer[IO_MAX_PATH_LENGTH]; + char buffer2[IO_MAX_PATH_LENGTH]; + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + int length; + + str_format(buffer, sizeof(buffer), "%s/*", dir); + MultiByteToWideChar(CP_UTF8, 0, buffer, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + + handle = FindFirstFileW(wBuffer, &finddata); + if(handle == INVALID_HANDLE_VALUE) + return; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + /* add all the entries */ + do + { + WideCharToMultiByte(CP_UTF8, 0, finddata.cFileName, -1, buffer2, sizeof(buffer2), NULL, NULL); + str_copy(buffer+length, buffer2, (int)sizeof(buffer)-length); + + CFsFileInfo info; + info.m_pName = buffer2; + info.m_TimeCreated = filetime_to_unixtime(&finddata.ftCreationTime); + info.m_TimeModified = filetime_to_unixtime(&finddata.ftLastWriteTime); + + if(cb(&info, (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0, type, user)) + break; + } + while(FindNextFileW(handle, &finddata)); + + FindClose(handle); +#else + struct dirent *entry; + time_t created = -1, modified = -1; + char buffer[IO_MAX_PATH_LENGTH]; + int length; + DIR *d = opendir(dir); + + if(!d) + return; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + while((entry = readdir(d)) != NULL) + { + CFsFileInfo info; + + str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + fs_file_time(buffer, &created, &modified); + + info.m_pName = entry->d_name; + info.m_TimeCreated = created; + info.m_TimeModified = modified; + + if(cb(&info, entry->d_type == DT_UNKNOWN ? fs_is_dir(buffer) : entry->d_type == DT_DIR, type, user)) + break; + } + + /* close the directory and return */ + closedir(d); +#endif +} + +int fs_storage_path(const char *appname, char *path, int max) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR *home = _wgetenv(L"APPDATA"); + char buffer[IO_MAX_PATH_LENGTH]; + if(!home) + return -1; + WideCharToMultiByte(CP_UTF8, 0, home, -1, buffer, sizeof(buffer), NULL, NULL); + str_format(path, max, "%s/%s", buffer, appname); + return 0; +#else + char *home = getenv("HOME"); + int i; + char *xdgdatahome = getenv("XDG_DATA_HOME"); + char xdgpath[max]; + + if(!home) + return -1; + +#if defined(CONF_PLATFORM_MACOSX) + str_format(path, max, "%s/Library/Application Support/%s", home, appname); + return 0; +#endif + + /* old folder location */ + str_format(path, max, "%s/.%s", home, appname); + for(i = str_length(home)+2; path[i]; i++) + path[i] = tolower(path[i]); + + if(!xdgdatahome) + { + /* use default location */ + str_format(xdgpath, max, "%s/.local/share/%s", home, appname); + for(i = str_length(home)+14; xdgpath[i]; i++) + xdgpath[i] = tolower(xdgpath[i]); + } + else + { + str_format(xdgpath, max, "%s/%s", xdgdatahome, appname); + for(i = str_length(xdgdatahome)+1; xdgpath[i]; i++) + xdgpath[i] = tolower(xdgpath[i]); + } + + /* check for old location / backward compatibility */ + if(fs_is_dir(path)) + { + /* use old folder path */ + /* for backward compatibility */ + return 0; + } + + str_format(path, max, "%s", xdgpath); + + return 0; +#endif +} + +int fs_makedir(const char *path) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + MultiByteToWideChar(CP_UTF8, 0, path, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + if(_wmkdir(wBuffer) == 0) + return 0; + if(errno == EEXIST) + return 0; + return -1; +#else + if(mkdir(path, 0755) == 0) + return 0; + if(errno == EEXIST) + return 0; + return -1; +#endif +} + +int fs_makedir_recursive(const char *path) +{ + char buffer[2048]; + int len; + int i; + str_copy(buffer, path, sizeof(buffer)); + len = str_length(buffer); + // ignore a leading slash + for(i = 1; i < len; i++) + { + char b = buffer[i]; + if(b == '/' || (b == '\\' && buffer[i-1] != ':')) + { + buffer[i] = 0; + if(fs_makedir(buffer) < 0) + { + return -1; + } + buffer[i] = b; + + } + } + return fs_makedir(path); +} + +int fs_is_dir(const char *path) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wPath[IO_MAX_PATH_LENGTH]; + MultiByteToWideChar(CP_UTF8, 0, path, -1, wPath, sizeof(wPath) / sizeof(WCHAR)); + DWORD attributes = GetFileAttributesW(wPath); + return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; +#else + struct stat sb; + if(stat(path, &sb) == -1) + return 0; + return S_ISDIR(sb.st_mode) ? 1 : 0; +#endif +} + +int fs_chdir(const char *path) +{ + if(fs_is_dir(path)) + { +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + MultiByteToWideChar(CP_UTF8, 0, path, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + if(_wchdir(wBuffer)) + return 1; + else + return 0; +#else + if(chdir(path)) + return 1; + else + return 0; +#endif + } + else + return 1; +} + +char *fs_getcwd(char *buffer, int buffer_size) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; +#endif + dbg_assert(buffer != 0, "buffer invalid"); + dbg_assert(buffer_size > 0, "buffer_size invalid"); +#if defined(CONF_FAMILY_WINDOWS) + if(_wgetcwd(wBuffer, buffer_size) == 0) + { + buffer[0] = '\0'; + return 0; + } + WideCharToMultiByte(CP_UTF8, 0, wBuffer, -1, buffer, buffer_size, NULL, NULL); + return buffer; +#else + if(getcwd(buffer, buffer_size) == 0) + { + buffer[0] = '\0'; + return 0; + } + return buffer; +#endif +} + +int fs_parent_dir(char *path) +{ + char *parent = 0; + for(; *path; ++path) + { + if(*path == '/' || *path == '\\') + parent = path; + } + + if(parent) + { + *parent = 0; + return 0; + } + return 1; +} + +int fs_remove(const char *filename) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wFilename[IO_MAX_PATH_LENGTH]; + MultiByteToWideChar(CP_UTF8, 0, filename, -1, wFilename, sizeof(wFilename) / sizeof(WCHAR)); + if(DeleteFileW(wFilename) == 0) + return 1; + return 0; +#else + if(remove(filename)) + return 1; + return 0; +#endif +} + +int fs_rename(const char *oldname, const char *newname) +{ +#if defined(CONF_FAMILY_WINDOWS) + WCHAR wOldname[IO_MAX_PATH_LENGTH]; + WCHAR wNewname[IO_MAX_PATH_LENGTH]; + MultiByteToWideChar(CP_UTF8, 0, oldname, -1, wOldname, sizeof(wOldname) / sizeof(WCHAR)); + MultiByteToWideChar(CP_UTF8, 0, newname, -1, wNewname, sizeof(wNewname) / sizeof(WCHAR)); + if(MoveFileExW(wOldname, wNewname, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) == 0) + return 1; + return 0; +#else + if(rename(oldname, newname)) + return 1; + return 0; +#endif +} + +int fs_read(const char *name, void **result, unsigned *result_len) +{ + IOHANDLE file = io_open(name, IOFLAG_READ); + *result = 0; + *result_len = 0; + if(!file) + { + return 1; + } + io_read_all(file, result, result_len); + io_close(file); + return 0; +} + +char *fs_read_str(const char *name) +{ + IOHANDLE file = io_open(name, IOFLAG_READ | IOFLAG_SKIP_BOM); + char *result; + if(!file) + { + return 0; + } + result = io_read_all_str(file); + io_close(file); + return result; +} + +int fs_file_time(const char *name, time_t *created, time_t *modified) +{ +#if defined(CONF_FAMILY_WINDOWS) + WIN32_FIND_DATAW finddata; + HANDLE handle; + WCHAR wBuffer[IO_MAX_PATH_LENGTH]; + + MultiByteToWideChar(CP_UTF8, 0, name, -1, wBuffer, sizeof(wBuffer) / sizeof(WCHAR)); + handle = FindFirstFileW(wBuffer, &finddata); + if(handle == INVALID_HANDLE_VALUE) + return 1; + + *created = filetime_to_unixtime(&finddata.ftCreationTime); + *modified = filetime_to_unixtime(&finddata.ftLastWriteTime); + FindClose(handle); +#elif defined(CONF_FAMILY_UNIX) + struct stat sb; + if(stat(name, &sb)) + return 1; + + *created = sb.st_ctime; + *modified = sb.st_mtime; +#else + #error not implemented +#endif + + return 0; +} + +void swap_endian(void *data, unsigned elem_size, unsigned num) +{ + char *src = (char*) data; + char *dst = src + (elem_size - 1); + + while(num) + { + unsigned n = elem_size>>1; + char tmp; + while(n) + { + tmp = *src; + *src = *dst; + *dst = tmp; + + src++; + dst--; + n--; + } + + src = src + (elem_size>>1); + dst = src + (elem_size - 1); + num--; + } +} + +int net_socket_read_wait(NETSOCKET sock, int time) +{ + struct timeval tv; + fd_set readfds; + int sockid; + + tv.tv_sec = 0; + tv.tv_usec = 1000*time; + sockid = 0; + + FD_ZERO(&readfds); + if(sock.ipv4sock >= 0) + { + FD_SET(sock.ipv4sock, &readfds); + sockid = sock.ipv4sock; + } + if(sock.ipv6sock >= 0) + { + FD_SET(sock.ipv6sock, &readfds); + if(sock.ipv6sock > sockid) + sockid = sock.ipv6sock; + } + + /* don't care about writefds and exceptfds */ + select(sockid+1, &readfds, NULL, NULL, &tv); + + if(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds)) + return 1; + + if(sock.ipv6sock >= 0 && FD_ISSET(sock.ipv6sock, &readfds)) + return 1; + + return 0; +} + +int time_timestamp() +{ + return time(0); +} + +int time_houroftheday() +{ + time_t time_data; + struct tm *time_info; + + time(&time_data); + time_info = localtime(&time_data); + return time_info->tm_hour; +} + +int time_season() +{ + time_t time_data; + struct tm *time_info; + + time(&time_data); + time_info = localtime(&time_data); + + if((time_info->tm_mon == 11 && time_info->tm_mday == 31) || (time_info->tm_mon == 0 && time_info->tm_mday == 1)) + { + return SEASON_NEWYEAR; + } + + switch(time_info->tm_mon) + { + case 11: + case 0: + case 1: + return SEASON_WINTER; + case 2: + case 3: + case 4: + return SEASON_SPRING; + case 5: + case 6: + case 7: + return SEASON_SUMMER; + case 8: + case 9: + case 10: + return SEASON_AUTUMN; + } + return SEASON_SPRING; // should never happen +} + +int time_isxmasday() +{ + time_t time_data; + struct tm *time_info; + + time(&time_data); + time_info = localtime(&time_data); + if(time_info->tm_mon == 11 && time_info->tm_mday >= 24 && time_info->tm_mday <= 26) + return 1; + return 0; +} + +int time_iseasterday() +{ + time_t time_data_now, time_data; + struct tm *time_info; + int Y, a, b, c, d, e, f, g, h, i, k, L, m, month, day, day_offset; + + time(&time_data_now); + time_info = localtime(&time_data_now); + + // compute Easter day (Sunday) using https://en.wikipedia.org/w/index.php?title=Computus&oldid=890710285#Anonymous_Gregorian_algorithm + Y = time_info->tm_year + 1900; + a = Y % 19; + b = Y / 100; + c = Y % 100; + d = b / 4; + e = b % 4; + f = (b + 8) / 25; + g = (b - f + 1) / 3; + h = (19 * a + b - d - g + 15) % 30; + i = c / 4; + k = c % 4; + L = (32 + 2 * e + 2 * i - h - k) % 7; + m = (a + 11 * h + 22 * L) / 451; + month = (h + L - 7 * m + 114) / 31; + day = ((h + L - 7 * m + 114) % 31) + 1; + + // (now-1d ≤ easter ≤ now+2d) <=> (easter-2d ≤ now ≤ easter+1d) <=> (Good Friday ≤ now ≤ Easter Monday) + for(day_offset = -1; day_offset <= 2; day_offset++) + { + time_data = time_data_now + day_offset*(60*60*24); + time_info = localtime(&time_data); + + if(time_info->tm_mon == month-1 && time_info->tm_mday == day) + return 1; + } + return 0; +} + +void str_append(char *dst, const char *src, int dst_size) +{ + int s; + int i = 0; + dbg_assert(dst_size > 0, "dst_size invalid"); + s = str_length(dst); + while(s < dst_size) + { + dst[s] = src[i]; + if(!src[i]) /* check for null termination */ + break; + s++; + i++; + } + + dst[dst_size-1] = 0; /* assure null termination */ +} + +void str_copy(char *dst, const char *src, int dst_size) +{ + dbg_assert(dst_size > 0, "dst_size invalid"); + + strncpy(dst, src, dst_size-1); + dst[dst_size-1] = 0; /* assure null termination */ +} + +void str_truncate(char *dst, int dst_size, const char *src, int truncation_len) +{ + int size = dst_size; + if(truncation_len < size) + { + size = truncation_len + 1; + } + str_copy(dst, src, size); +} + +int str_length(const char *str) +{ + return (int)strlen(str); +} + +void str_format(char *buffer, int buffer_size, const char *format, ...) +{ + va_list ap; + dbg_assert(buffer_size > 0, "buffer_size invalid"); + va_start(ap, format); + +#if defined(CONF_FAMILY_WINDOWS) && !defined(__GNUC__) + _vsprintf_p(buffer, buffer_size, format, ap); +#else + vsnprintf(buffer, buffer_size, format, ap); +#endif + + va_end(ap); + + buffer[buffer_size-1] = 0; /* assure null termination */ +} + + + +/* makes sure that the string only contains the characters between 32 and 127 */ +void str_sanitize_strong(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + *str &= 0x7f; + if(*str < 32) + *str = 32; + str++; + } +} + +/* makes sure that the string only contains the characters between 32 and 255 */ +void str_sanitize_cc(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + if(*str < 32) + *str = ' '; + str++; + } +} + +/* check if the string contains '..' (parent directory) paths */ +int str_path_unsafe(const char *str) +{ + // State machine. 0 means that we're at the beginning + // of a new directory/filename, and a positive number represents the number of + // dots ('.') we found. -1 means we encountered a different character + // since the last path separator (or the beginning of the string). + int parse_counter = 0; + while(*str) + { + if(*str == '\\' || *str == '/') + { + // A path separator. Check how many dots we found since + // the last path separator. + // + // Two dots => ".." contained in the path. Return an + // error. + if(parse_counter == 2) + return -1; + else + parse_counter = 0; + } + else if(parse_counter >= 0) + { + // If we have not encountered a non-dot character since + // the last path separator, count the dots. + if(*str == '.') + parse_counter++; + else + parse_counter = -1; + } + + ++str; + } + // If there's a ".." at the end, fail too. + if(parse_counter == 2) + return -1; + return 0; +} + +/* makes sure that the string only contains the characters between 32 and 255 + \r\n\t */ +void str_sanitize(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + if(*str < 32 && !(*str == '\r') && !(*str == '\n') && !(*str == '\t')) + *str = ' '; + str++; + } +} + +/* removes all forbidden windows/unix characters in filenames*/ +char* str_sanitize_filename(char* aName) +{ + char *str = (char *)aName; + while(*str) + { + // replace forbidden characters with a whispace + if(*str == '/' || *str == '<' || *str == '>' || *str == ':' || *str == '"' + || *str == '/' || *str == '\\' || *str == '|' || *str == '?' || *str == '*') + *str = ' '; + str++; + } + str_clean_whitespaces(aName); + return aName; +} + +/* removes leading and trailing spaces and limits the use of multiple spaces */ +void str_clean_whitespaces(char *str_in) +{ + char *read = str_in; + char *write = str_in; + + /* skip initial whitespace */ + while(*read == ' ') + read++; + + /* end of read string is detected in the loop */ + while(1) + { + /* skip whitespace */ + int found_whitespace = 0; + for(; *read == ' '; read++) + found_whitespace = 1; + /* if not at the end of the string, put a found whitespace here */ + if(*read) + { + if(found_whitespace) + *write++ = ' '; + *write++ = *read++; + } + else + { + *write = 0; + break; + } + } +} + +/* removes leading and trailing spaces */ +void str_clean_whitespaces_simple(char *str_in) +{ + char *read = str_in; + char *write = str_in; + + /* skip initial whitespace */ + while(*read == ' ') + read++; + + /* end of read string is detected in the loop */ + while(1) + { + /* skip whitespace */ + int found_whitespace = 0; + for(; *read == ' ' && !found_whitespace; read++) + found_whitespace = 1; + /* if not at the end of the string, put a found whitespace here */ + if(*read) + { + if(found_whitespace) + *write++ = ' '; + *write++ = *read++; + } + else + { + *write = 0; + break; + } + } +} + +char *str_skip_to_whitespace(char *str) +{ + while(*str && (*str != ' ' && *str != '\t' && *str != '\n')) + str++; + return str; +} + +const char *str_skip_to_whitespace_const(const char *str) +{ + while(*str && (*str != ' ' && *str != '\t' && *str != '\n')) + str++; + return str; +} + +char *str_skip_whitespaces(char *str) +{ + while(*str && (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r')) + str++; + return str; +} + +const char *str_skip_whitespaces_const(const char *str) +{ + while(*str && (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r')) + str++; + return str; +} + +/* case */ +int str_comp_nocase(const char *a, const char *b) +{ +#if defined(CONF_FAMILY_WINDOWS) && !defined(__GNUC__) + return _stricmp(a,b); +#else + return strcasecmp(a,b); +#endif +} + +int str_comp_nocase_num(const char *a, const char *b, const int num) +{ +#if defined(CONF_FAMILY_WINDOWS) && !defined(__GNUC__) + return _strnicmp(a, b, num); +#else + return strncasecmp(a, b, num); +#endif +} + +int str_comp(const char *a, const char *b) +{ + return strcmp(a, b); +} + +int str_comp_num(const char *a, const char *b, const int num) +{ + return strncmp(a, b, num); +} + +int str_comp_filenames(const char *a, const char *b) +{ + int result; + + for(; *a && *b; ++a, ++b) + { + if(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9') + { + result = 0; + do + { + if(!result) + result = *a - *b; + ++a; ++b; + } + while(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9'); + + if(*a >= '0' && *a <= '9') + return 1; + else if(*b >= '0' && *b <= '9') + return -1; + else if(result) + return result; + } + + if(tolower(*a) != tolower(*b)) + break; + } + return tolower(*a) - tolower(*b); +} + +const char *str_startswith_nocase(const char *str, const char *prefix) +{ + int prefixl = str_length(prefix); + if(str_comp_nocase_num(str, prefix, prefixl) == 0) + { + return str + prefixl; + } + else + { + return 0; + } +} + +const char *str_startswith(const char *str, const char *prefix) +{ + int prefixl = str_length(prefix); + if(str_comp_num(str, prefix, prefixl) == 0) + { + return str + prefixl; + } + else + { + return 0; + } +} + +const char *str_endswith_nocase(const char *str, const char *suffix) +{ + int strl = str_length(str); + int suffixl = str_length(suffix); + const char *strsuffix; + if(strl < suffixl) + { + return 0; + } + strsuffix = str + strl - suffixl; + if(str_comp_nocase(strsuffix, suffix) == 0) + { + return strsuffix; + } + else + { + return 0; + } +} + +const char *str_endswith(const char *str, const char *suffix) +{ + int strl = str_length(str); + int suffixl = str_length(suffix); + const char *strsuffix; + if(strl < suffixl) + { + return 0; + } + strsuffix = str + strl - suffixl; + if(str_comp(strsuffix, suffix) == 0) + { + return strsuffix; + } + else + { + return 0; + } +} + +const char *str_find_nocase(const char *haystack, const char *needle) +{ + while(*haystack) /* native implementation */ + { + const char *a = haystack; + const char *b = needle; + while(*a && *b && tolower(*a) == tolower(*b)) + { + a++; + b++; + } + if(!(*b)) + return haystack; + haystack++; + } + + return 0; +} + + +const char *str_find(const char *haystack, const char *needle) +{ + while(*haystack) /* native implementation */ + { + const char *a = haystack; + const char *b = needle; + while(*a && *b && *a == *b) + { + a++; + b++; + } + if(!(*b)) + return haystack; + haystack++; + } + + return 0; +} + +void str_hex(char *dst, int dst_size, const void *data, int data_size) +{ + static const char hex[] = "0123456789ABCDEF"; + int b; + + for(b = 0; b < data_size && b < dst_size/4-4; b++) + { + dst[b*3] = hex[((const unsigned char *)data)[b]>>4]; + dst[b*3+1] = hex[((const unsigned char *)data)[b]&0xf]; + dst[b*3+2] = ' '; + dst[b*3+3] = 0; + } +} + +int str_is_number(const char *str) +{ + while(*str) + { + if(!(*str >= '0' && *str <= '9')) + return -1; + str++; + } + return 0; +} +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif +void str_timestamp_ex(time_t time_data, char *buffer, int buffer_size, const char *format) +{ + struct tm *time_info; + dbg_assert(buffer_size > 0, "buffer_size invalid"); + time_info = localtime(&time_data); + strftime(buffer, buffer_size, format, time_info); + buffer[buffer_size-1] = 0; /* assure null termination */ +} + +void str_timestamp_format(char *buffer, int buffer_size, const char *format) +{ + time_t time_data; + time(&time_data); + str_timestamp_ex(time_data, buffer, buffer_size, format); +} + +void str_timestamp(char *buffer, int buffer_size) +{ + str_timestamp_format(buffer, buffer_size, FORMAT_NOSPACE); +} +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +int str_span(const char *str, const char *set) +{ + return strcspn(str, set); +} + +int mem_comp(const void *a, const void *b, int size) +{ + return memcmp(a,b,size); +} + +int mem_has_null(const void *block, unsigned size) +{ + const unsigned char *bytes = block; + unsigned i; + for(i = 0; i < size; i++) + { + if(bytes[i] == 0) + { + return 1; + } + } + return 0; +} + +void net_stats(NETSTATS *stats_inout) +{ + *stats_inout = network_stats; +} + +int str_isspace(char c) { return c == ' ' || c == '\n' || c == '\t'; } + +char str_uppercase(char c) +{ + if(c >= 'a' && c <= 'z') + return 'A' + (c-'a'); + return c; +} + +int str_toint(const char *str) { return atoi(str); } +float str_tofloat(const char *str) { return atof(str); } + +int str_utf8_is_whitespace(int code) +{ + // check if unicode is not empty + if(code > 0x20 && code != 0xA0 && code != 0x034F && (code < 0x2000 || code > 0x200F) && (code < 0x2028 || code > 0x202F) && + (code < 0x205F || code > 0x2064) && (code < 0x206A || code > 0x206F) && code != 0x3000 && (code < 0xFE00 || code > 0xFE0F) && + code != 0xFEFF && (code < 0xFFF9 || code > 0xFFFC)) + { + return 0; + } + return 1; +} + +const char *str_utf8_skip_whitespaces(const char *str) +{ + const char *str_old; + int code; + + while(*str) + { + str_old = str; + code = str_utf8_decode(&str); + + if(!str_utf8_is_whitespace(code)) + { + return str_old; + } + } + + return str; +} + +void str_utf8_trim_whitespaces_right(char *str) +{ + int cursor = str_length(str); + const char *last = str + cursor; + while(str_utf8_is_whitespace(str_utf8_decode(&last))) + { + str[cursor] = 0; + cursor = str_utf8_rewind(str, cursor); + last = str + cursor; + if(cursor == 0) + { + break; + } + } +} + +static int str_utf8_isstart(char c) +{ + if((c&0xC0) == 0x80) /* 10xxxxxx */ + return 0; + return 1; +} + +int str_utf8_rewind(const char *str, int cursor) +{ + while(cursor) + { + cursor--; + if(str_utf8_isstart(*(str + cursor))) + break; + } + return cursor; +} + +int str_utf8_forward(const char *str, int cursor) +{ + const char *buf = str + cursor; + if(!buf[0]) + return cursor; + + if((*buf&0x80) == 0x0) /* 0xxxxxxx */ + return cursor+1; + else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ + { + if(!buf[1]) return cursor+1; + return cursor+2; + } + else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ + { + if(!buf[1]) return cursor+1; + if(!buf[2]) return cursor+2; + return cursor+3; + } + else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ + { + if(!buf[1]) return cursor+1; + if(!buf[2]) return cursor+2; + if(!buf[3]) return cursor+3; + return cursor+4; + } + + /* invalid */ + return cursor+1; +} + +int str_utf8_encode(char *ptr, int chr) +{ + /* encode */ + if(chr <= 0x7F) + { + ptr[0] = (char)chr; + return 1; + } + else if(chr <= 0x7FF) + { + ptr[0] = 0xC0|((chr>>6)&0x1F); + ptr[1] = 0x80|(chr&0x3F); + return 2; + } + else if(chr <= 0xFFFF) + { + ptr[0] = 0xE0|((chr>>12)&0x0F); + ptr[1] = 0x80|((chr>>6)&0x3F); + ptr[2] = 0x80|(chr&0x3F); + return 3; + } + else if(chr <= 0x10FFFF) + { + ptr[0] = 0xF0|((chr>>18)&0x07); + ptr[1] = 0x80|((chr>>12)&0x3F); + ptr[2] = 0x80|((chr>>6)&0x3F); + ptr[3] = 0x80|(chr&0x3F); + return 4; + } + + return 0; +} + +int str_utf8_decode(const char **ptr) +{ + const char *buf = *ptr; + int ch = 0; + + do + { + if((*buf&0x80) == 0x0) /* 0xxxxxxx */ + { + ch = *buf; + buf++; + } + else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ + { + ch = (*buf++ & 0x3F) << 6; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F); + if(ch < 0x80 || ch > 0x7FF) ch = -1; + } + else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ + { + ch = (*buf++ & 0x1F) << 12; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F) << 6; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F); + if(ch < 0x800 || ch > 0xFFFF) ch = -1; + } + else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ + { + ch = (*buf++ & 0x0F) << 18; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F) << 12; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F) << 6; if(!(*buf) || (*buf&0xC0) != 0x80) break; + ch += (*buf++ & 0x3F); + if(ch < 0x10000 || ch > 0x10FFFF) ch = -1; + } + else + { + /* invalid */ + buf++; + break; + } + + *ptr = buf; + return ch; + } while(0); + + /* out of bounds */ + *ptr = buf; + return -1; + +} + +int str_utf8_check(const char *str) +{ + while(*str) + { + if((*str&0x80) == 0x0) + str++; + else if((*str&0xE0) == 0xC0 && (*(str+1)&0xC0) == 0x80) + str += 2; + else if((*str&0xF0) == 0xE0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80) + str += 3; + else if((*str&0xF8) == 0xF0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80 && (*(str+3)&0xC0) == 0x80) + str += 4; + else + return 0; + } + return 1; +} + +void str_utf8_copy_num(char *dst, const char *src, int dst_size, int num) +{ + int new_cursor; + int cursor = 0; + dbg_assert(dst_size > 0, "dst_size invalid"); + + while(src[cursor] && num > 0) + { + new_cursor = str_utf8_forward(src, cursor); + if(new_cursor >= dst_size) // reserve 1 byte for the null termination + break; + else + cursor = new_cursor; + --num; + } + + str_copy(dst, src, cursor < dst_size ? cursor+1 : dst_size); +} + +void str_utf8_stats(const char *str, int max_size, int max_count, int *size, int *count) +{ + *size = 0; + *count = 0; + while(*size < max_size && *count < max_count) + { + int new_size = str_utf8_forward(str, *size); + if(new_size == *size || new_size >= max_size) + break; + *size = new_size; + ++(*count); + } +} + +unsigned str_quickhash(const char *str) +{ + unsigned hash = 5381; + for(; *str; str++) + hash = ((hash << 5) + hash) + (*str); /* hash * 33 + c */ + return hash; +} + +struct SECURE_RANDOM_DATA +{ + int initialized; +#if defined(CONF_FAMILY_WINDOWS) + HCRYPTPROV provider; +#else + IOHANDLE urandom; +#endif +}; + +static struct SECURE_RANDOM_DATA secure_random_data = { 0 }; + +int secure_random_init() +{ + if(secure_random_data.initialized) + { + return 0; + } +#if defined(CONF_FAMILY_WINDOWS) + if(CryptAcquireContext(&secure_random_data.provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + { + secure_random_data.initialized = 1; + return 0; + } + else + { + return 1; + } +#else + secure_random_data.urandom = io_open("/dev/urandom", IOFLAG_READ); + if(secure_random_data.urandom) + { + secure_random_data.initialized = 1; + return 0; + } + else + { + return 1; + } +#endif +} + +int secure_random_uninit() +{ + if(!secure_random_data.initialized) + { + return 0; + } +#if defined(CONF_FAMILY_WINDOWS) + if(CryptReleaseContext(secure_random_data.provider, 0)) + { + secure_random_data.initialized = 0; + return 0; + } + else + { + return 1; + } +#else + if(!io_close(secure_random_data.urandom)) + { + secure_random_data.initialized = 0; + return 0; + } + else + { + return 1; + } +#endif +} + +void secure_random_fill(void *bytes, unsigned length) +{ + if(!secure_random_data.initialized) + { + dbg_msg("secure", "called secure_random_fill before secure_random_init"); + dbg_break(); + } +#if defined(CONF_FAMILY_WINDOWS) + if(!CryptGenRandom(secure_random_data.provider, length, bytes)) + { + dbg_msg("secure", "CryptGenRandom failed, last_error=%lu", GetLastError()); + dbg_break(); + } +#else + if(length != io_read(secure_random_data.urandom, bytes, length)) + { + dbg_msg("secure", "io_read returned with a short read"); + dbg_break(); + } +#endif +} + +int pid() +{ +#if defined(CONF_FAMILY_WINDOWS) + return _getpid(); +#else + return getpid(); +#endif +} + +void cmdline_fix(int *argc, const char ***argv) +{ +#if defined(CONF_FAMILY_WINDOWS) + int wide_argc = 0; + WCHAR **wide_argv = CommandLineToArgvW(GetCommandLineW(), &wide_argc); + dbg_assert(wide_argv != NULL, "CommandLineToArgvW failure"); + + int total_size = 0; + + for(int i = 0; i < wide_argc; i++) + { + int size = WideCharToMultiByte(CP_UTF8, 0, wide_argv[i], -1, NULL, 0, NULL, NULL); + dbg_assert(size != 0, "WideCharToMultiByte failure"); + total_size += size; + } + + char **new_argv = (char **)malloc((wide_argc + 1) * sizeof(*new_argv)); + new_argv[0] = (char *)malloc(total_size); + mem_zero(new_argv[0], total_size); + + int remaining_size = total_size; + for(int i = 0; i < wide_argc; i++) + { + int size = WideCharToMultiByte(CP_UTF8, 0, wide_argv[i], -1, new_argv[i], remaining_size, NULL, NULL); + dbg_assert(size != 0, "WideCharToMultiByte failure"); + + remaining_size -= size; + new_argv[i + 1] = new_argv[i] + size; + } + + new_argv[wide_argc] = 0; + *argc = wide_argc; + *argv = (const char **)new_argv; +#endif +} + +void cmdline_free(int argc, const char **argv) +{ +#if defined(CONF_FAMILY_WINDOWS) + free((void *)*argv); + free((char **)argv); +#endif +} + +int bytes_be_to_int(const unsigned char *bytes) +{ + int Result; + unsigned char *pResult = (unsigned char *)&Result; + for(unsigned i = 0; i < sizeof(int); i++) + { +#if defined(CONF_ARCH_ENDIAN_BIG) + pResult[i] = bytes[i]; +#else + pResult[i] = bytes[sizeof(int) - i - 1]; +#endif + } + return Result; +} + +void int_to_bytes_be(unsigned char *bytes, int value) +{ + const unsigned char *pValue = (const unsigned char *)&value; + for(unsigned i = 0; i < sizeof(int); i++) + { +#if defined(CONF_ARCH_ENDIAN_BIG) + bytes[i] = pValue[i]; +#else + bytes[sizeof(int) - i - 1] = pValue[i]; +#endif + } +} + +unsigned bytes_be_to_uint(const unsigned char *bytes) +{ + return ((bytes[0] & 0xffu) << 24u) | ((bytes[1] & 0xffu) << 16u) | ((bytes[2] & 0xffu) << 8u) | (bytes[3] & 0xffu); +} + +void uint_to_bytes_be(unsigned char *bytes, unsigned value) +{ + bytes[0] = (value >> 24u) & 0xffu; + bytes[1] = (value >> 16u) & 0xffu; + bytes[2] = (value >> 8u) & 0xffu; + bytes[3] = value & 0xffu; +} + + +#if defined(__cplusplus) +} +#endif diff --git a/src/base/system.h b/src/base/system.h new file mode 100644 index 000000000..9c5efadcf --- /dev/null +++ b/src/base/system.h @@ -0,0 +1,1892 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +/* + Title: OS Abstraction +*/ + +#ifndef BASE_SYSTEM_H +#define BASE_SYSTEM_H + +#include "detect.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __GNUC__ +#define GNUC_ATTRIBUTE(x) __attribute__(x) +#else +#define GNUC_ATTRIBUTE(x) +#endif + +/* Group: Debug */ +/* + + Function: dbg_assert + Breaks into the debugger based on a test. + + Parameters: + test - Result of the test. + msg - Message that should be printed if the test fails. + + See Also: + +*/ +void dbg_assert(int test, const char *msg); +#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) +void dbg_assert_imp(const char *filename, int line, int test, const char *msg); + + +#ifdef __clang_analyzer__ +#include +#undef dbg_assert +#define dbg_assert(test,msg) assert(test) +#endif + +/* + Function: dbg_break + Breaks into the debugger. + + See Also: + +*/ +void dbg_break(); + +/* + Function: dbg_msg + + Prints a debug message. + + Parameters: + sys - A string that describes what system the message belongs to + fmt - A printf styled format string. + + See Also: + +*/ +void dbg_msg(const char *sys, const char *fmt, ...) +GNUC_ATTRIBUTE((format(printf, 2, 3))); + +/* Group: Memory */ + +/* + Function: mem_alloc + Allocates memory. + + Parameters: + size - Size of the needed block. + + Returns: + Returns a pointer to the newly allocated block. Returns a + null pointer if the memory couldn't be allocated. + + Remarks: + - The behavior when passing 0 as size is unspecified. + + See Also: + +*/ +void *mem_alloc(unsigned size); + +/* + Function: mem_free + Frees a block allocated through . + + See Also: + +*/ +void mem_free(void *block); + +/* + Function: mem_copy + Copies a a memory block. + + Parameters: + dest - Destination. + source - Source to copy. + size - Size of the block to copy. + + Remarks: + - This functions DOES NOT handles cases where source and + destination is overlapping. + + See Also: + +*/ +void mem_copy(void *dest, const void *source, unsigned size); + +/* + Function: mem_move + Copies a a memory block + + Parameters: + dest - Destination + source - Source to copy + size - Size of the block to copy + + Remarks: + - This functions handles cases where source and destination + is overlapping + + See Also: + +*/ +void mem_move(void *dest, const void *source, unsigned size); + +/* + Function: mem_zero + Sets a complete memory block to 0 + + Parameters: + block - Pointer to the block to zero out + size - Size of the block +*/ +void mem_zero(void *block, unsigned size); + +/* + Function: mem_comp + Compares two blocks of memory + + Parameters: + a - First block of data + b - Second block of data + size - Size of the data to compare + + Returns: + <0 - Block a is lesser then block b + 0 - Block a is equal to block b + >0 - Block a is greater then block b +*/ +int mem_comp(const void *a, const void *b, int size); + +/* + Function: mem_has_null + Checks whether a block of memory contains null bytes. + + Parameters: + block - Pointer to the block to check for nulls. + size - Size of the block. + + Returns: + 1 - The block has a null byte. + 0 - The block does not have a null byte. +*/ +int mem_has_null(const void *block, unsigned size); + +/* Group: File IO */ +enum { + IOFLAG_READ = 1, + IOFLAG_WRITE = 2, + IOFLAG_APPEND = 4, + IOFLAG_SKIP_BOM = 8, + + IOSEEK_START = 0, + IOSEEK_CUR = 1, + IOSEEK_END = 2, + + IO_MAX_PATH_LENGTH = 512, +}; + +typedef struct IOINTERNAL *IOHANDLE; + +/* + Function: io_open + Opens a file. + + Parameters: + filename - File to open. + flags - A set of flags. IOFLAG_READ, IOFLAG_WRITE, IOFLAG_APPEND, IOFLAG_SKIP_BOM. + + Returns: + Returns a handle to the file on success and 0 on failure. + +*/ +IOHANDLE io_open(const char *filename, int flags); + +/* + Function: io_read + Reads data into a buffer from a file. + + Parameters: + io - Handle to the file to read data from. + buffer - Pointer to the buffer that will receive the data. + size - Number of bytes to read from the file. + + Returns: + Number of bytes read. + +*/ +unsigned io_read(IOHANDLE io, void *buffer, unsigned size); + +/* + Function: io_read_all + Reads the rest of the file into a buffer. + + Parameters: + io - Handle to the file to read data from. + result - Receives the file's remaining contents. + result_len - Receives the file's remaining length. + + Remarks: + - Does NOT guarantee that there are no internal null bytes. + - Guarantees that result will contain zero-termination. + - The result must be freed after it has been used. +*/ +void io_read_all(IOHANDLE io, void **result, unsigned *result_len); + +/* + Function: io_read_all_str + Reads the rest of the file into a zero-terminated buffer with + no internal null bytes. + + Parameters: + io - Handle to the file to read data from. + + Returns: + The file's remaining contents or null on failure. + + Remarks: + - Guarantees that there are no internal null bytes. + - Guarantees that result will contain zero-termination. + - The result must be freed after it has been used. +*/ +char *io_read_all_str(IOHANDLE io); + +/* + Function: io_unread_byte + "Unreads" a single byte, making it available for future read + operations. + + Parameters: + io - Handle to the file to unread the byte from. + byte - Byte to unread. + + Returns: + Returns 0 on success and 1 on failure. + +*/ +unsigned io_unread_byte(IOHANDLE io, unsigned char byte); + +/* + Function: io_skip + Skips data in a file. + + Parameters: + io - Handle to the file. + size - Number of bytes to skip. + + Returns: + Number of bytes skipped. +*/ +unsigned io_skip(IOHANDLE io, int size); + +/* + Function: io_write + Writes data from a buffer to file. + + Parameters: + io - Handle to the file. + buffer - Pointer to the data that should be written. + size - Number of bytes to write. + + Returns: + Number of bytes written. +*/ +unsigned io_write(IOHANDLE io, const void *buffer, unsigned size); + +/* + Function: io_write_newline + Writes newline to file. + + Parameters: + io - Handle to the file. + + Returns: + Number of bytes written. +*/ +unsigned io_write_newline(IOHANDLE io); + +/* + Function: io_seek + Seeks to a specified offset in the file. + + Parameters: + io - Handle to the file. + offset - Offset from pos to stop. + origin - Position to start searching from. + + Returns: + Returns 0 on success. +*/ +int io_seek(IOHANDLE io, int offset, int origin); + +/* + Function: io_tell + Gets the current position in the file. + + Parameters: + io - Handle to the file. + + Returns: + Returns the current position. -1L if an error occured. +*/ +long int io_tell(IOHANDLE io); + +/* + Function: io_length + Gets the total length of the file. Resetting cursor to the beginning + + Parameters: + io - Handle to the file. + + Returns: + Returns the total size. -1L if an error occured. +*/ +long int io_length(IOHANDLE io); + +/* + Function: io_close + Closes a file. + + Parameters: + io - Handle to the file. + + Returns: + Returns 0 on success. +*/ +int io_close(IOHANDLE io); + +/* + Function: io_flush + Empties all buffers and writes all pending data. + + Parameters: + io - Handle to the file. + + Returns: + Returns 0 on success. +*/ +int io_flush(IOHANDLE io); + + +/* + Function: io_stdin + Returns an to the standard input. +*/ +IOHANDLE io_stdin(); + +/* + Function: io_stdout + Returns an to the standard output. +*/ +IOHANDLE io_stdout(); + +/* + Function: io_stderr + Returns an to the standard error. +*/ +IOHANDLE io_stderr(); + + +/* Group: Threads */ + +/* + Function: thread_sleep + Suspends the current thread for a given period. + + Parameters: + milliseconds - Number of milliseconds to sleep. +*/ +void thread_sleep(int milliseconds); + +/* + Function: thread_init + Creates a new thread. + + Parameters: + threadfunc - Entry point for the new thread. + user - Pointer to pass to the thread. + +*/ +void *thread_init(void (*threadfunc)(void *), void *user); + +/* + Function: thread_wait + Waits for a thread to be done or destroyed. + + Parameters: + thread - Thread to wait for. +*/ +void thread_wait(void *thread); + +/* + Function: thread_destroy + Frees resources associated with a thread handle. + + Parameters: + thread - Thread handle to destroy. + + Remarks: + - The thread must have already terminated normally. + - Detached threads must not be destroyed with this function. +*/ +void thread_destroy(void *thread); + +/* + Function: thread_yield + Yield the current threads execution slice. +*/ +void thread_yield(); + +/* + Function: thread_detach + Puts the thread in the detached state, guaranteeing that + resources of the thread will be freed immediately when the + thread terminates. + + Parameters: + thread - Thread to detach + + Remarks: + - This invalidates the thread handle, hence it must not be + used after detaching the thread. +*/ +void thread_detach(void *thread); + +/* + Function: cpu_relax + Lets the cpu relax a bit. +*/ +void cpu_relax(); + +/* Group: Locks */ +typedef void* LOCK; + +LOCK lock_create(); +void lock_destroy(LOCK lock); + +int lock_trylock(LOCK lock); +void lock_wait(LOCK lock); +void lock_unlock(LOCK lock); + + +/* Group: Semaphores */ + +#if !defined(CONF_PLATFORM_MACOSX) + #if defined(CONF_FAMILY_UNIX) + #include + typedef sem_t SEMAPHORE; + #elif defined(CONF_FAMILY_WINDOWS) + typedef void* SEMAPHORE; + #else + #error missing sempahore implementation + #endif + + void semaphore_init(SEMAPHORE *sem); + void semaphore_wait(SEMAPHORE *sem); + void semaphore_signal(SEMAPHORE *sem); + void semaphore_destroy(SEMAPHORE *sem); +#endif + +/* Group: Timer */ +#ifdef __GNUC__ +/* if compiled with -pedantic-errors it will complain about long + not being a C90 thing. +*/ +__extension__ typedef long long int64; +#else +typedef long long int64; +#endif +/* + Function: time_get + Fetches a sample from a high resolution timer. + + Returns: + Current value of the timer. + + Remarks: + To know how fast the timer is ticking, see . +*/ +int64 time_get(); + +/* + Function: time_freq + Returns the frequency of the high resolution timer. + + Returns: + Returns the frequency of the high resolution timer. +*/ +int64 time_freq(); + +/* + Function: time_timestamp + Retrieves the current time as a UNIX timestamp + + Returns: + The time as a UNIX timestamp +*/ +int time_timestamp(); + +/* + Function: time_houroftheday + Retrieves the hours since midnight (0..23) + + Returns: + The current hour of the day +*/ +int time_houroftheday(); + + +enum +{ + SEASON_SPRING = 0, + SEASON_SUMMER, + SEASON_AUTUMN, + SEASON_WINTER, + SEASON_NEWYEAR +}; + +/* + Function: time_season + Retrieves the current season of the year. + + Returns: + one of the SEASON_* enum literals +*/ +int time_season(); + +/* + Function: time_isxmasday + Checks if it's xmas + + Returns: + 1 - if it's a xmas day + 0 - if not +*/ +int time_isxmasday(); + +/* + Function: time_iseasterday + Checks if today is in between Good Friday and Easter Monday (Gregorian calendar) + + Returns: + 1 - if it's egg time + 0 - if not +*/ +int time_iseasterday(); + +/* Group: Network General */ +typedef struct +{ + int type; + int ipv4sock; + int ipv6sock; +} NETSOCKET; + +enum +{ + NETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX + + NETADDR_SIZE_IPV4 = 4, + NETADDR_SIZE_IPV6 = 16, + + NETTYPE_INVALID = 0, + NETTYPE_IPV4 = 1, + NETTYPE_IPV6 = 2, + NETTYPE_LINK_BROADCAST = 4, + NETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6 +}; + +typedef struct +{ + unsigned int type; + unsigned char ip[NETADDR_SIZE_IPV6]; + unsigned short port; + unsigned short reserved; +} NETADDR; + +/* + Function: net_invalidate_socket + Invalidates a socket. + + Remarks: + You should close the socket before invalidating it. +*/ +void net_invalidate_socket(NETSOCKET *socket); +/* + Function: net_init + Initiates network functionality. + + Returns: + Returns 0 on success, + + Remarks: + You must call this function before using any other network + functions. +*/ +int net_init(); + +/* + Function: net_host_lookup + Does a hostname lookup by name and fills out the passed + NETADDR struct with the recieved details. + + Returns: + 0 on success. +*/ +int net_host_lookup(const char *hostname, NETADDR *addr, int types); + +/* + Function: net_addr_comp + Compares two network addresses. + + Parameters: + a - Address to compare + b - Address to compare to. + check_port - compares port or not + + Returns: + 0 - Address a is equal to address b + -1 - Address a differs from address b +*/ +int net_addr_comp(const NETADDR *a, const NETADDR *b, int check_port); + +/* + Function: net_addr_str + Turns a network address into a representive string. + + Parameters: + addr - Address to turn into a string. + string - Buffer to fill with the string. + max_length - Maximum size of the string. + add_port - add port to string or not + + Remarks: + - The string will always be zero terminated + +*/ +void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port); + +/* + Function: net_addr_from_str + Turns string into a network address. + + Returns: + 0 on success + + Parameters: + addr - Address to fill in. + string - String to parse. +*/ +int net_addr_from_str(NETADDR *addr, const char *string); + +/* Group: Network UDP */ + +/* + Function: net_udp_create + Creates a UDP socket and binds it to a port. + + Parameters: + bindaddr - Address to bind the socket to. + use_random_port - use a random port + + Returns: + On success it returns an handle to the socket. On failure it + returns NETSOCKET_INVALID. +*/ +NETSOCKET net_udp_create(NETADDR bindaddr, int use_random_port); + +/* + Function: net_udp_send + Sends a packet over an UDP socket. + + Parameters: + sock - Socket to use. + addr - Where to send the packet. + data - Pointer to the packet data to send. + size - Size of the packet. + + Returns: + On success it returns the number of bytes sent. Returns -1 + on error. +*/ +int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size); + +/* + Function: net_udp_recv + Receives a packet over an UDP socket. + + Parameters: + sock - Socket to use. + addr - Pointer to an NETADDR that will receive the address. + data - Pointer to a buffer that will receive the data. + maxsize - Maximum size to receive. + + Returns: + On success it returns the number of bytes recived. Returns -1 + on error. +*/ +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize); + +/* + Function: net_udp_close + Closes an UDP socket. + + Parameters: + sock - Socket to close. + + Returns: + Returns 0 on success. -1 on error. +*/ +int net_udp_close(NETSOCKET sock); + + +/* Group: Network TCP */ + +/* + Function: net_tcp_create + Creates a TCP socket. + + Parameters: + bindaddr - Address to bind the socket to. + + Returns: + On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID. +*/ +NETSOCKET net_tcp_create(NETADDR bindaddr); + +/* + Function: net_tcp_set_linger + Sets behaviour when closing the socket. + + Parameters: + sock - Socket to use. + state - What to do when closing the socket. + 1 abort connection on close. + 0 shutdown the connection properly on close. + + Returns: + Returns 0 on success. +*/ +int net_tcp_set_linger(NETSOCKET sock, int state); + +/* + Function: net_tcp_listen + Makes the socket start listening for new connections. + + Parameters: + sock - Socket to start listen to. + backlog - Size of the queue of incomming connections to keep. + + Returns: + Returns 0 on success. +*/ +int net_tcp_listen(NETSOCKET sock, int backlog); + +/* + Function: net_tcp_accept + Polls a listning socket for a new connection. + + Parameters: + sock - Listning socket to poll. + new_sock - Pointer to a socket to fill in with the new socket. + addr - Pointer to an address that will be filled in the remote address (optional, can be NULL). + + Returns: + Returns a non-negative integer on success. Negative integer on failure. +*/ +int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *addr); + +/* + Function: net_tcp_connect + Connects one socket to another. + + Parameters: + sock - Socket to connect. + addr - Address to connect to. + + Returns: + Returns 0 on success. + +*/ +int net_tcp_connect(NETSOCKET sock, const NETADDR *addr); + +/* + Function: net_tcp_send + Sends data to a TCP stream. + + Parameters: + sock - Socket to send data to. + data - Pointer to the data to send. + size - Size of the data to send. + + Returns: + Number of bytes sent. Negative value on failure. +*/ +int net_tcp_send(NETSOCKET sock, const void *data, int size); + +/* + Function: net_tcp_recv + Recvives data from a TCP stream. + + Parameters: + sock - Socket to recvive data from. + data - Pointer to a buffer to write the data to + max_size - Maximum of data to write to the buffer. + + Returns: + Number of bytes recvived. Negative value on failure. When in + non-blocking mode, it returns 0 when there is no more data to + be fetched. +*/ +int net_tcp_recv(NETSOCKET sock, void *data, int maxsize); + +/* + Function: net_tcp_close + Closes a TCP socket. + + Parameters: + sock - Socket to close. + + Returns: + Returns 0 on success. Negative value on failure. +*/ +int net_tcp_close(NETSOCKET sock); + +/* Group: Strings */ + +/* + Function: str_append + Appends a string to another. + + Parameters: + dst - Pointer to a buffer that contains a string. + src - String to append. + dst_size - Size of the buffer of the dst string. + + Remarks: + - The strings are treated as zero-terminated strings. + - Garantees that dst string will contain zero-termination. +*/ +void str_append(char *dst, const char *src, int dst_size); + +/* + Function: str_copy + Copies a string to another. + + Parameters: + dst - Pointer to a buffer that shall receive the string. + src - String to be copied. + dst_size - Size of the buffer dst. + + Remarks: + - The strings are treated as zero-terminated strings. + - Garantees that dst string will contain zero-termination. +*/ +void str_copy(char *dst, const char *src, int dst_size); + +/* + Function: str_truncate + Truncates a string to a given length. + + Parameters: + dst - Pointer to a buffer that shall receive the string. + dst_size - Size of the buffer dst. + src - String to be truncated. + truncation_len - Maximum length of the returned string (not + counting the zero termination). + + Remarks: + - The strings are treated as zero-terminated strings. + - Garantees that dst string will contain zero-termination. +*/ +void str_truncate(char *dst, int dst_size, const char *src, int truncation_len); + +/* + Function: str_length + Returns the length of a zero terminated string. + + Parameters: + str - Pointer to the string. + + Returns: + Length of string in bytes excluding the zero termination. +*/ +int str_length(const char *str); + +/* + Function: str_format + Performs printf formatting into a buffer. + + Parameters: + buffer - Pointer to the buffer to receive the formatted string. + buffer_size - Size of the buffer. + format - printf formatting string. + ... - Parameters for the formatting. + + Remarks: + - See the C manual for syntax for the printf formatting string. + - The strings are treated as zero-termineted strings. + - Guarantees that dst string will contain zero-termination. +*/ +void str_format(char *buffer, int buffer_size, const char *format, ...) +GNUC_ATTRIBUTE((format(printf, 3, 4))); + +/* + Function: str_sanitize_strong + Replaces all characters below 32 and above 127 with whitespace. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_sanitize_strong(char *str); + +/* + Function: str_sanitize_cc + Replaces all characters below 32 with whitespace. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_sanitize_cc(char *str); + +/* + Function: str_sanitize + Replaces all characters below 32 with whitespace with + exception to \t, \n and \r. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_sanitize(char *str); + +/* + Function: str_sanitize_filename + Replaces all forbidden Windows/Unix characters with whitespace + or nothing if leading or trailing. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +char *str_sanitize_filename(char *name); + +/* + Function: str_path_unsafe + Check if the string contains '..' (parent directory) paths. + + Parameters: + str - String to check. + + Returns: + Returns 0 if the path is safe, -1 otherwise. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int str_path_unsafe(const char *str); + +/* + Function: str_clean_whitespaces + Removes leading and trailing spaces and limits the use of multiple spaces. + + Parameters: + str - String to clean up + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_clean_whitespaces(char *str); + +/* + Function: str_clean_whitespaces_simple + Removes leading and trailing spaces + + Parameters: + str - String to clean up + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_clean_whitespaces_simple(char *str); + +/* + Function: str_skip_to_whitespace + Skips leading non-whitespace characters(all but ' ', '\t', '\n', '\r'). + + Parameters: + str - Pointer to the string. + + Returns: + Pointer to the first whitespace character found + within the string. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +char *str_skip_to_whitespace(char *str); + +/* + Function: str_skip_to_whitespace_const + See str_skip_to_whitespace. +*/ +const char *str_skip_to_whitespace_const(const char *str); + +/* + Function: str_skip_whitespaces + Skips leading whitespace characters(' ', '\t', '\n', '\r'). + + Parameters: + str - Pointer to the string. + + Returns: + Pointer to the first non-whitespace character found + within the string. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +char *str_skip_whitespaces(char *str); + +/* + Function: str_skip_whitespaces_const + See str_skip_whitespaces. +*/ +const char *str_skip_whitespaces_const(const char *str); + +/* + Function: str_comp_nocase + Compares to strings case insensitive. + + Parameters: + a - String to compare. + b - String to compare. + + Returns: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-terminated strings. +*/ +int str_comp_nocase(const char *a, const char *b); + +/* + Function: str_comp_nocase_num + Compares up to num characters of two strings case insensitive. + + Parameters: + a - String to compare. + b - String to compare. + num - Maximum characters to compare + + Returns: + <0 - String a is lesser than string b + 0 - String a is equal to string b + >0 - String a is greater than string b + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-terminated strings. +*/ +int str_comp_nocase_num(const char *a, const char *b, const int num); + +/* + Function: str_comp + Compares to strings case sensitive. + + Parameters: + a - String to compare. + b - String to compare. + + Returns: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int str_comp(const char *a, const char *b); + +/* + Function: str_comp_num + Compares up to num characters of two strings case sensitive. + + Parameters: + a - String to compare. + b - String to compare. + num - Maximum characters to compare + + Returns: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int str_comp_num(const char *a, const char *b, const int num); + +/* + Function: str_comp_filenames + Compares two strings case sensitive, digit chars will be compared as numbers. + + Parameters: + a - String to compare. + b - String to compare. + + Returns: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int str_comp_filenames(const char *a, const char *b); + +/* + Function: str_startswith_nocase + Checks case insensitive whether the string begins with a certain prefix. + + Parameter: + str - String to check. + prefix - Prefix to look for. + + Returns: + A pointer to the string str after the string prefix, or 0 if + the string prefix isn't a prefix of the string str. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_startswith_nocase(const char *str, const char *prefix); + + +/* + Function: str_startswith + Checks case sensitive whether the string begins with a certain prefix. + + Parameter: + str - String to check. + prefix - Prefix to look for. + + Returns: + A pointer to the string str after the string prefix, or 0 if + the string prefix isn't a prefix of the string str. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_startswith(const char *str, const char *prefix); + +/* + Function: str_endswith_nocase + Checks case insensitive whether the string ends with a certain suffix. + + Parameter: + str - String to check. + suffix - Suffix to look for. + + Returns: + A pointer to the beginning of the suffix in the string str, or + 0 if the string suffix isn't a suffix of the string str. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_endswith_nocase(const char *str, const char *suffix); + +/* + Function: str_endswith + Checks case sensitive whether the string ends with a certain suffix. + + Parameter: + str - String to check. + suffix - Suffix to look for. + + Returns: + A pointer to the beginning of the suffix in the string str, or + 0 if the string suffix isn't a suffix of the string str. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_endswith(const char *str, const char *suffix); + +/* + Function: str_find_nocase + Finds a string inside another string case insensitive. + + Parameters: + haystack - String to search in + needle - String to search for + + Returns: + A pointer into haystack where the needle was found. + Returns NULL of needle could not be found. + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-terminated strings. +*/ +const char *str_find_nocase(const char *haystack, const char *needle); + +/* + Function: str_find + Finds a string inside another string case sensitive. + + Parameters: + haystack - String to search in + needle - String to search for + + Returns: + A pointer into haystack where the needle was found. + Returns NULL of needle could not be found. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_find(const char *haystack, const char *needle); + +/* + Function: str_hex + Takes a datablock and generates a hexstring of it. + + Parameters: + dst - Buffer to fill with hex data + dst_size - size of the buffer + data - Data to turn into hex + data - Size of the data + + Remarks: + - The destination buffer will be zero-terminated +*/ +void str_hex(char *dst, int dst_size, const void *data, int data_size); + +/* + Function: str_is_number + Check if the string contains only digits. + + Parameters: + str - String to check. + + Returns: + Returns 0 if it's a number, -1 otherwise. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int str_is_number(const char *pstr); + +/* + Function: str_timestamp + Copies a time stamp in the format year-month-day_hour-minute-second to the string. + + Parameters: + buffer - Pointer to a buffer that shall receive the time stamp string. + buffer_size - Size of the buffer. + + Remarks: + - Guarantees that buffer string will contain zero-termination. +*/ +void str_timestamp(char *buffer, int buffer_size); +void str_timestamp_format(char *buffer, int buffer_size, const char *format) +GNUC_ATTRIBUTE((format(strftime, 3, 0))); +void str_timestamp_ex(time_t time, char *buffer, int buffer_size, const char *format) +GNUC_ATTRIBUTE((format(strftime, 4, 0))); + +/* + Function: str_span + Returns the length of the minimum initial segment that doesn't contain characters in set + + Parameters: + str - String to search in + set - Set of characters to stop on + + Remarks: + - Also stops on '\0' +*/ +int str_span(const char *str, const char *set); + +#define FORMAT_TIME "%H:%M:%S" +#define FORMAT_SPACE "%Y-%m-%d %H:%M:%S" +#define FORMAT_NOSPACE "%Y-%m-%d_%H-%M-%S" + +/* Group: Filesystem */ + +/* + Function: fs_listdir + Lists the files in a directory + + Parameters: + dir - Directory to list + cb - Callback function to call for each entry + type - Type of the directory + user - Pointer to give to the callback +*/ +typedef int (*FS_LISTDIR_CALLBACK)(const char *name, int is_dir, int dir_type, void *user); +void fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user); + +typedef struct +{ + const char *m_pName; + time_t m_TimeCreated; // seconds since UNIX Epoch + time_t m_TimeModified; // seconds since UNIX Epoch +} CFsFileInfo; + +/* + Function: fs_listdir_fileinfo + Lists the files in a directory and gets additional file information + + Parameters: + dir - Directory to list + cb - Callback function to call for each entry + type - Type of the directory + user - Pointer to give to the callback +*/ +typedef int (*FS_LISTDIR_CALLBACK_FILEINFO)(const CFsFileInfo *info, int is_dir, int dir_type, void *user); +void fs_listdir_fileinfo(const char *dir, FS_LISTDIR_CALLBACK_FILEINFO cb, int type, void *user); + +/* + Function: fs_makedir + Creates a directory + + Parameters: + path - Directory to create + + Returns: + Returns 0 on success. Negative value on failure. + + Remarks: + Does not create several directories if needed. "a/b/c" will result + in a failure if b or a does not exist. +*/ +int fs_makedir(const char *path); + +/* + Function: fs_makedir_recursive + Recursively create directories + + Parameters: + path - Path to create + + Returns: + Returns 0 on success. Negative value on failure. +*/ +int fs_makedir_recursive(const char *path); + + +/* + Function: fs_storage_path + Fetches per user configuration directory. + + Returns: + Returns 0 on success. Negative value on failure. + + Remarks: + - Returns ~/.appname on UNIX based systems + - Returns ~/Library/Applications Support/appname on Mac OS X + - Returns %APPDATA%/Appname on Windows based systems +*/ +int fs_storage_path(const char *appname, char *path, int max); + +/* + Function: fs_is_dir + Checks if directory exists + + Returns: + Returns 1 on success, 0 on failure. +*/ +int fs_is_dir(const char *path); + +/* + Function: fs_chdir + Changes current working directory + + Returns: + Returns 0 on success, 1 on failure. +*/ +int fs_chdir(const char *path); + +/* + Function: fs_getcwd + Gets the current working directory. + + Parameters: + buffer - Pointer to a buffer that will hold the result. + buffer_size - The size of the buffer in bytes. + + Returns: + Returns a pointer to the buffer on success, 0 on failure. + On success, the buffer contains the result as a zero-terminated string. + On failure, the buffer contains an empty zero-terminated string. + +*/ +char *fs_getcwd(char *buffer, int buffer_size); + +/* + Function: fs_parent_dir + Get the parent directory of a directory + + Parameters: + path - The directory string + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The string is treated as zero-terminated string. +*/ +int fs_parent_dir(char *path); + +/* + Function: fs_remove + Deletes the file with the specified name. + + Parameters: + filename - The file to delete + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int fs_remove(const char *filename); + +/* + Function: fs_rename + Renames the file or directory. If the paths differ the file will be moved. + + Parameters: + oldname - The actual name + newname - The new name + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int fs_rename(const char *oldname, const char *newname); + +/* + Function: fs_read + Reads a whole file into memory and returns its contents. + + Parameters: + name - The filename to read. + result - Receives the file's contents. + result_len - Receives the file's length. + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - Does NOT guarantee that there are no internal null bytes. + - Guarantees that result will contain zero-termination. + - The result must be freed after it has been used. +*/ +int fs_read(const char *name, void **result, unsigned *result_len); + +/* + Function: fs_read_str + Reads a whole file into memory and returns its contents, + guaranteeing a null-terminated string with no internal null + bytes. + + Parameters: + name - The filename to read. + + Returns: + Returns the file's contents on success, null on failure. + + Remarks: + - Guarantees that there are no internal null bytes. + - Guarantees that result will contain zero-termination. + - The result must be freed after it has been used. +*/ +char *fs_read_str(const char *name); + +/* + Function: fs_file_time + Gets the creation and the last modification date of a file. + + Parameters: + name - The filename. + created - Pointer to time_t + modified - Pointer to time_t + + Returns: + 0 on success non-zero on failure + + Remarks: + - Returned time is in seconds since UNIX Epoch +*/ +int fs_file_time(const char *name, time_t *created, time_t *modified); + +/* + Group: Undocumented +*/ + + +/* + Function: net_tcp_connect_non_blocking + + DOCTODO: serp +*/ +int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr); + +/* + Function: net_set_non_blocking + + DOCTODO: serp +*/ +int net_set_non_blocking(NETSOCKET sock); + +/* + Function: net_set_non_blocking + + DOCTODO: serp +*/ +int net_set_blocking(NETSOCKET sock); + +/* + Function: net_errno + + DOCTODO: serp +*/ +int net_errno(); + +/* + Function: net_would_block + + DOCTODO: serp +*/ +int net_would_block(); + +int net_socket_read_wait(NETSOCKET sock, int time); + +void swap_endian(void *data, unsigned elem_size, unsigned num); + + +typedef void (*DBG_LOGGER)(const char *line); +void dbg_logger(DBG_LOGGER logger); + +void dbg_logger_stdout(); +void dbg_logger_debugger(); +void dbg_logger_file(const char *filename); +void dbg_logger_filehandle(IOHANDLE handle); + +#if defined(CONF_FAMILY_WINDOWS) +void dbg_console_init(); +void dbg_console_cleanup(); +#endif + +typedef struct +{ + int sent_packets; + int sent_bytes; + int recv_packets; + int recv_bytes; +} NETSTATS; + + +void net_stats(NETSTATS *stats); + +int str_toint(const char *str); +float str_tofloat(const char *str); +int str_isspace(char c); +char str_uppercase(char c); +unsigned str_quickhash(const char *str); + +enum +{ + UTF8_BYTE_LENGTH = 4 +}; +/* + Function: str_utf8_is_whitespace + Check if the unicode is an utf8 whitespace. + + Parameters: + code - unicode. + + Returns: + Returns 1 on success, 0 on failure. +*/ +int str_utf8_is_whitespace(int code); + +/* + Function: str_utf8_skip_whitespaces + Skips leading utf8 whitespace characters. + + Parameters: + str - Pointer to the string. + + Returns: + Pointer to the first non-whitespace character found + within the string. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +const char *str_utf8_skip_whitespaces(const char *str); + +/* + Function: str_utf8_trim_whitespaces_right + Clears trailing utf8 whitespace characters from a string. + + Parameters: + str - Pointer to the string. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +void str_utf8_trim_whitespaces_right(char *str); + +/* + Function: str_utf8_rewind + Moves a cursor backwards in an utf8 string + + Parameters: + str - utf8 string + cursor - position in the string + + Returns: + New cursor position. + + Remarks: + - Won't move the cursor less then 0 +*/ +int str_utf8_rewind(const char *str, int cursor); + +/* + Function: str_utf8_forward + Moves a cursor forwards in an utf8 string + + Parameters: + str - utf8 string + cursor - position in the string + + Returns: + New cursor position. + + Remarks: + - Won't move the cursor beyond the zero termination marker +*/ +int str_utf8_forward(const char *str, int cursor); + +/* + Function: str_utf8_decode + Decodes an utf8 character + + Parameters: + ptr - pointer to an utf8 string. this pointer will be moved forward + + Returns: + Unicode value for the character. -1 for invalid characters and 0 for end of string. + + Remarks: + - This function will also move the pointer forward. +*/ +int str_utf8_decode(const char **ptr); + +/* + Function: str_utf8_encode + Encode an utf8 character + + Parameters: + ptr - Pointer to a buffer that should recive the data. Should be able to hold at least 4 bytes. + + Returns: + Number of bytes put into the buffer. + + Remarks: + - Does not do zero termination of the string. +*/ +int str_utf8_encode(char *ptr, int chr); + +/* + Function: str_utf8_check + Checks if a strings contains just valid utf8 characters. + + Parameters: + str - Pointer to a possible utf8 string. + + Returns: + 0 - invalid characters found. + 1 - only valid characters found. + + Remarks: + - The string is treated as zero-terminated utf8 string. +*/ +int str_utf8_check(const char *str); + +/* + Function: str_utf8_copy_num + Copies a number of utf8 characters from one string to another. + + Parameters: + dst - Pointer to a buffer that shall receive the string. + src - String to be copied. + dst_size - Size of the buffer dst. + num - maximum number of utf8 characters to be copied. + + Remarks: + - The strings are treated as zero-terminated strings. + - Garantees that dst string will contain zero-termination. +*/ +void str_utf8_copy_num(char *dst, const char *src, int dst_size, int num); + +/* + Function: str_utf8_stats + Determines the byte size and utf8 character count of a utf8 string. + + Parameters: + str - Pointer to the string. + max_size - Maximum number of bytes to count. + max_count - Maximum number of utf8 characters to count. + size - Pointer to store size (number of non-zero bytes) of the string. + count - Pointer to store count of utf8 characters of the string. + + Remarks: + - The string is treated as zero-terminated utf8 string. + - It's the user's responsibility to make sure the bounds are aligned. +*/ +void str_utf8_stats(const char *str, int max_size, int max_count, int *size, int *count); + +/* + Function: secure_random_init + Initializes the secure random module. + You *MUST* check the return value of this function. + + Returns: + 0 - Initialization succeeded. + 1 - Initialization failed. +*/ +int secure_random_init(); + +/* + Function: secure_random_uninit + Uninitializes the secure random module. + + Returns: + 0 - Uninitialization succeeded. + 1 - Uninitialization failed. +*/ +int secure_random_uninit(); + +/* + Function: secure_random_fill + Fills the buffer with the specified amount of random bytes. + + Parameters: + bytes - Pointer to the start of the buffer. + length - Length of the buffer. +*/ +void secure_random_fill(void *bytes, unsigned length); + +/* + Function: pid + Gets the process ID of the current process + + Returns: + The process ID of the current process. +*/ +int pid(); + +/* + Function: cmdline_fix + Fixes the command line arguments to be encoded in UTF-8 on all + systems. + + Parameters: + argc - A pointer to the argc parameter that was passed to the main function. + argv - A pointer to the argv parameter that was passed to the main function. + + Remarks: + - You need to call cmdline_free once you're no longer using the + results. +*/ +void cmdline_fix(int *argc, const char ***argv); + +/* + Function: cmdline_free + Frees memory that was allocated by cmdline_fix. + + Parameters: + argc - The argc obtained from cmdline_fix. + argv - The argv obtained from cmdline_fix. + +*/ +void cmdline_free(int argc, const char **argv); + +/* + Function: bytes_be_to_int + Packs 4 big endian bytes into an int + + Returns: + The packed int + + Remarks: + - Assumes the passed array is 4 bytes + - Assumes int is 4 bytes +*/ +int bytes_be_to_int(const unsigned char *bytes); + +/* + Function: int_to_bytes_be + Packs an int into 4 big endian bytes + + Remarks: + - Assumes the passed array is 4 bytes + - Assumes int is 4 bytes +*/ +void int_to_bytes_be(unsigned char *bytes, int value); + +/* + Function: bytes_be_to_uint + Packs 4 big endian bytes into an unsigned + + Returns: + The packed unsigned + + Remarks: + - Assumes the passed array is 4 bytes + - Assumes unsigned is 4 bytes +*/ +unsigned bytes_be_to_uint(const unsigned char *bytes); + +/* + Function: uint_to_bytes_be + Packs an unsigned into 4 big endian bytes + + Remarks: + - Assumes the passed array is 4 bytes + - Assumes unsigned is 4 bytes +*/ +void uint_to_bytes_be(unsigned char *bytes, unsigned value); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/base/tl/algorithm.h b/src/base/tl/algorithm.h new file mode 100644 index 000000000..41367dbd3 --- /dev/null +++ b/src/base/tl/algorithm.h @@ -0,0 +1,142 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ALGORITHM_H +#define BASE_TL_ALGORITHM_H + +#include + +#include "range.h" + +/* + insert 4 + v + 1 2 3 4 5 6 + +*/ + + +template +R partition_linear(R range, T value) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + concept_sorted::check(range); + + for(; !range.empty(); range.pop_front()) + { + if(!(range.front() < value)) + return range; + } + return range; +} + + +template +R partition_binary(R range, T value) +{ + concept_empty::check(range); + concept_index::check(range); + concept_size::check(range); + concept_slice::check(range); + concept_sorted::check(range); + + if(range.empty()) + return range; + if(range.back() < value) + return R(); + + while(range.size() > 1) + { + unsigned pivot = (range.size()-1)/2; + if(range.index(pivot) < value) + range = range.slice(pivot+1, range.size()-1); + else + range = range.slice(0, pivot+1); + } + return range; +} + +template +R find_linear(R range, T value) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + for(; !range.empty(); range.pop_front()) + if(value == range.front()) + break; + return range; +} + +template +R find_binary(R range, T value) +{ + range = partition_binary(range, value); + if(range.empty()) return range; + if(range.front() == value) return range; + return R(); +} + + +template +void sort_bubble(R range) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + concept_backwarditeration::check(range); + + // slow bubblesort :/ + for(; !range.empty(); range.pop_back()) + { + R section = range; + typename R::type *prev = §ion.front(); + section.pop_front(); + for(; !section.empty(); section.pop_front()) + { + typename R::type *cur = §ion.front(); + if(*cur < *prev) + std::swap(*cur, *prev); + prev = cur; + } + } +} + +/* +template +void sort_quick(R range) +{ + concept_index::check(range); +}*/ + +template +void sort(R range, Cmp cmp) +{ + std::stable_sort(&range.front(), &range.back()+1, cmp); +} + +template +void sort(R range) +{ + std::stable_sort(&range.front(), &range.back()+1); +} + +template +bool sort_verify(R range) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + + typename R::type *prev = &range.front(); + range.pop_front(); + for(; !range.empty(); range.pop_front()) + { + typename R::type *cur = &range.front(); + + if(*cur < *prev) + return false; + prev = cur; + } + + return true; +} + +#endif // BASE_TL_ALGORITHM_H diff --git a/src/base/tl/allocator.h b/src/base/tl/allocator.h new file mode 100644 index 000000000..01fc9c6c9 --- /dev/null +++ b/src/base/tl/allocator.h @@ -0,0 +1,17 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ALLOCATOR_H +#define BASE_TL_ALLOCATOR_H + +template +class allocator_default +{ +public: + static T *alloc() { return new T; } + static void free(T *p) { delete p; } + + static T *alloc_array(int size) { return new T [size]; } + static void free_array(T *p) { delete [] p; } +}; + +#endif // BASE_TL_ALLOCATOR_H diff --git a/src/base/tl/array.h b/src/base/tl/array.h new file mode 100644 index 000000000..c5d2a87a8 --- /dev/null +++ b/src/base/tl/array.h @@ -0,0 +1,344 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ARRAY_H +#define BASE_TL_ARRAY_H + +#include "range.h" +#include "allocator.h" + + +/* + Class: array + Normal dynamic array class + + Remarks: + - Grows 50% each time it needs to fit new items + - Use set_size() if you know how many elements + - Use optimize() to reduce the needed space. +*/ +template > +class array : private ALLOCATOR +{ + void init() + { + list = 0x0; + clear(); + } + +public: + typedef plain_range range; + + /* + Function: array constructor + */ + array() + { + init(); + } + + /* + Function: array copy constructor + */ + array(const array &other) + { + init(); + set_size(other.size()); + for(int i = 0; i < size(); i++) + (*this)[i] = other[i]; + } + + + /* + Function: array destructor + */ + ~array() + { + ALLOCATOR::free_array(list); + list = 0x0; + } + + + /* + Function: delete_all + + Remarks: + - Invalidates ranges + */ + void delete_all() + { + for(int i = 0; i < size(); i++) + delete list[i]; + clear(); + } + + + /* + Function: clear + + Remarks: + - Invalidates ranges + */ + void clear() + { + ALLOCATOR::free_array(list); + list_size = 1; + list = ALLOCATOR::alloc_array(list_size); + num_elements = 0; + } + + /* + Function: size + */ + int size() const + { + return num_elements; + } + + /* + Function: remove_index_fast + + Remarks: + - Invalidates ranges + */ + void remove_index_fast(int index) + { + list[index] = list[num_elements-1]; + set_size(size()-1); + } + + /* + Function: remove_fast + + Remarks: + - Invalidates ranges + */ + void remove_fast(const T& item) + { + for(int i = 0; i < size(); i++) + if(list[i] == item) + { + remove_index_fast(i); + return; + } + } + + /* + Function: remove_index + + Remarks: + - Invalidates ranges + */ + void remove_index(int index) + { + for(int i = index+1; i < num_elements; i++) + list[i-1] = list[i]; + + set_size(size()-1); + } + + /* + Function: remove + + Remarks: + - Invalidates ranges + */ + bool remove(const T& item) + { + for(int i = 0; i < size(); i++) + if(list[i] == item) + { + remove_index(i); + return true; + } + return false; + } + + /* + Function: add + Adds an item to the array. + + Arguments: + item - Item to add. + + Remarks: + - Invalidates ranges + - See remarks about how the array grows. + */ + int add(const T& item) + { + incsize(); + set_size(size()+1); + list[num_elements-1] = item; + return num_elements-1; + } + + /* + Function: insert + Inserts an item into the array at a specified location. + + Arguments: + item - Item to insert. + r - Range where to insert the item + + Remarks: + - Invalidates ranges + - See remarks about how the array grows. + */ + int insert(const T& item, range r) + { + if(r.empty()) + return add(item); + + int index = (int)(&r.front()-list); + incsize(); + set_size(size()+1); + + for(int i = num_elements-1; i > index; i--) + list[i] = list[i-1]; + + list[index] = item; + + return num_elements-1; + } + + /* + Function: operator[] + */ + T& operator[] (int index) + { + return list[index]; + } + + /* + Function: const operator[] + */ + const T& operator[] (int index) const + { + return list[index]; + } + + /* + Function: base_ptr + */ + T *base_ptr() + { + return list; + } + + /* + Function: base_ptr + */ + const T *base_ptr() const + { + return list; + } + + /* + Function: set_size + Resizes the array to the specified size. + + Arguments: + new_size - The new size for the array. + */ + void set_size(int new_size) + { + if(list_size < new_size) + alloc(new_size); + num_elements = new_size; + } + + /* + Function: hint_size + Allocates the number of elements wanted but + does not increase the list size. + + Arguments: + hint - Size to allocate. + + Remarks: + - If the hint is smaller then the number of elements, nothing will be done. + - Invalidates ranges + */ + void hint_size(int hint) + { + if(num_elements < hint) + alloc(hint); + } + + + /* + Function: optimize + Removes unnecessary data, returns how many bytes was earned. + + Remarks: + - Invalidates ranges + */ + int optimize() + { + int before = memusage(); + alloc(num_elements); + return before - memusage(); + } + + /* + Function: memusage + Returns how much memory this dynamic array is using + */ + int memusage() const + { + return sizeof(array) + sizeof(T)*list_size; + } + + /* + Function: operator=(array) + + Remarks: + - Invalidates ranges + */ + array &operator = (const array &other) + { + set_size(other.size()); + for(int i = 0; i < size(); i++) + (*this)[i] = other[i]; + return *this; + } + + /* + Function: all + Returns a range that contains the whole array. + */ + range all() const { return range(list, list+num_elements); } +protected: + + void incsize() + { + if(num_elements == list_size) + { + if(list_size < 2) + alloc(list_size+1); + else + alloc(list_size+list_size/2); + } + } + + void alloc(int new_len) + { + list_size = new_len; + T *new_list = ALLOCATOR::alloc_array(list_size); + + int end = num_elements < list_size ? num_elements : list_size; + for(int i = 0; i < end; i++) + new_list[i] = list[i]; + + ALLOCATOR::free_array(list); + + num_elements = num_elements < list_size ? num_elements : list_size; + list = new_list; + } + + T *list; + int list_size; + int num_elements; +}; + +#endif // BASE_TL_ARRAY_H diff --git a/src/base/tl/range.h b/src/base/tl/range.h new file mode 100644 index 000000000..2adc86cab --- /dev/null +++ b/src/base/tl/range.h @@ -0,0 +1,224 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_RANGE_H +#define BASE_TL_RANGE_H + +#include + +/* + Group: Range concepts +*/ + +/* + Concept: concept_empty + + template + struct range + { + bool empty() const; + }; +*/ +struct concept_empty +{ + template static void check(T &t) { if(0) t.empty(); } +}; + +/* + Concept: concept_index + + template + struct range + { + T &index(size_t); + }; +*/ +struct concept_index +{ + template static void check(T &t) { if(0) t.index(0); } +}; + +/* + Concept: concept_size + + template + struct range + { + size_t size(); + }; +*/ +struct concept_size +{ + template static void check(T &t) { if(0) t.size(); } +}; + +/* + Concept: concept_slice + + template + struct range + { + range slice(size_t start, size_t count); + }; +*/ +struct concept_slice +{ + template static void check(T &t) { if(0) t.slice(0, 0); } +}; + +/* + Concept: concept_sorted + + template + struct range + { + void sorted(); + }; +*/ +struct concept_sorted +{ + template static void check(T &t) { if(0) t.sorted(); } +}; + +/* + Concept: concept_forwarditeration + Checks for the front and pop_front methods + + template + struct range + { + void pop_front(); + T &front() const; + }; +*/ +struct concept_forwarditeration +{ + template static void check(T &t) { if(0) { t.front(); t.pop_front(); } }; +}; + +/* + Concept: concept_backwarditeration + Checks for the back and pop_back methods + + template + struct range + { + void pop_back(); + T &back() const; + }; +*/ +struct concept_backwarditeration +{ + template static void check(T &t) { if(0) { t.back(); t.pop_back(); } }; +}; + + +/* + Group: Range classes +*/ + + +/* + Class: plain_range + + Concepts: + + + + + +*/ +template +class plain_range +{ +public: + typedef T type; + plain_range() + { + begin = 0x0; + end = 0x0; + } + + plain_range(T *b, T *e) + { + begin = b; + end = e; + } + + bool empty() const { return begin >= end; } + void pop_front() { dbg_assert(!empty(), "empty"); begin++; } + void pop_back() { dbg_assert(!empty(), "empty"); end--; } + T& front() { dbg_assert(!empty(), "empty"); return *begin; } + T& back() { dbg_assert(!empty(), "empty"); return *(end-1); } + T& index(unsigned i) { dbg_assert(i < (unsigned)(end-begin), "out of range"); return begin[i]; } + unsigned size() const { return (unsigned)(end-begin); } + plain_range slice(unsigned startindex, unsigned endindex) + { + return plain_range(begin+startindex, begin+endindex); + } + +protected: + T *begin; + T *end; +}; + +/* + Class: plain_range_sorted + + Concepts: + Same as but with these additions: + +*/ +template +class plain_range_sorted : public plain_range +{ + typedef plain_range parent; +public: + /* sorted concept */ + void sorted() const { } + + plain_range_sorted() + {} + + plain_range_sorted(T *b, T *e) + : parent(b, e) + {} + + plain_range_sorted slice(unsigned start, unsigned count) + { + return plain_range_sorted(parent::begin+start, parent::begin+start+count); + } +}; + +template +class reverse_range +{ +private: + reverse_range() {} +public: + typedef typename R::type type; + + reverse_range(R r) + { + range = r; + } + + reverse_range(const reverse_range &other) { range = other.range; } + + + bool empty() const { return range.empty(); } + void pop_front() { range.pop_back(); } + void pop_back() { range.pop_front(); } + type& front() { return range.back(); } + type& back() { return range.front(); } + + R range; +}; + +template reverse_range reverse(R range) { + return reverse_range(range); +} +template R reverse(reverse_range range) { + return range.range; +} + +#endif // BASE_TL_RANGE_H diff --git a/src/base/tl/sorted_array.h b/src/base/tl/sorted_array.h new file mode 100644 index 000000000..40edadd4c --- /dev/null +++ b/src/base/tl/sorted_array.h @@ -0,0 +1,50 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_SORTED_ARRAY_H +#define BASE_TL_SORTED_ARRAY_H + +#include "algorithm.h" +#include "array.h" + +template > +class sorted_array : public array +{ + typedef array parent; + + // insert and size is not allowed + int insert(const T& item, typename parent::range r) { dbg_break(); return 0; } + int set_size(int new_size) { dbg_break(); return 0; } + +public: + typedef plain_range_sorted range; + + int add(const T& item) + { + return parent::insert(item, partition_binary(all(), item)); + } + + int add_unsorted(const T& item) + { + return parent::add(item); + } + + void sort_range() + { + if(parent::size() > 0) + sort(all()); + } + + template + void sort_range_by(R cmp) + { + sort(all(), cmp); + } + + /* + Function: all + Returns a sorted range that contains the whole array. + */ + range all() const { return range(parent::list, parent::list+parent::num_elements); } +}; + +#endif // BASE_TL_SORTED_ARRAY_H diff --git a/src/base/tl/string.h b/src/base/tl/string.h new file mode 100644 index 000000000..295e72c39 --- /dev/null +++ b/src/base/tl/string.h @@ -0,0 +1,69 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_STRING_H +#define BASE_TL_STRING_H + +#include "allocator.h" + +template +class string_base : private ALLOCATOR +{ + char *str; + int length; + + void reset() + { + str = 0; length = 0; + } + + void free() + { + ALLOCATOR::free_array(str); + reset(); + } + + void copy(const char *other_str, int other_length) + { + length = other_length; + str = ALLOCATOR::alloc_array(length+1); + mem_copy(str, other_str, length+1); + } + + void copy(const string_base &other) + { + if(!other.str) + return; + copy(other.str, other.length); + } + +public: + string_base() { reset(); } + string_base(const char *other_str) { copy(other_str, str_length(other_str)); } + string_base(const string_base &other) { reset(); copy(other); } + ~string_base() { free(); } + + string_base &operator = (const char *other) + { + free(); + if(other) + copy(other, str_length(other)); + return *this; + } + + string_base &operator = (const string_base &other) + { + free(); + copy(other); + return *this; + } + + bool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; } + operator const char *() const { return str; } + + const char *cstr() const { return str; } +}; + +/* normal allocated string */ +typedef string_base > string; + +#endif // BASE_TL_STRING_H diff --git a/src/base/tl/threading.h b/src/base/tl/threading.h new file mode 100644 index 000000000..49a174b42 --- /dev/null +++ b/src/base/tl/threading.h @@ -0,0 +1,121 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_THREADING_H +#define BASE_TL_THREADING_H + +#include "../system.h" + +/* + atomic_inc - should return the value after increment + atomic_dec - should return the value after decrement + atomic_compswap - should return the value before the eventual swap + sync_barrier - creates a full hardware fence +*/ + +#if defined(__GNUC__) + + inline unsigned atomic_inc(volatile unsigned *pValue) + { + return __sync_add_and_fetch(pValue, 1); + } + + inline unsigned atomic_dec(volatile unsigned *pValue) + { + return __sync_add_and_fetch(pValue, -1); + } + + inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) + { + return __sync_val_compare_and_swap(pValue, comperand, value); + } + + inline void sync_barrier() + { + __sync_synchronize(); + } + +#elif defined(_MSC_VER) + #include + + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + + inline unsigned atomic_inc(volatile unsigned *pValue) + { + return _InterlockedIncrement((volatile long *)pValue); + } + + inline unsigned atomic_dec(volatile unsigned *pValue) + { + return _InterlockedDecrement((volatile long *)pValue); + } + + inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) + { + return _InterlockedCompareExchange((volatile long *)pValue, (long)value, (long)comperand); + } + + inline void sync_barrier() + { + MemoryBarrier(); + } +#else + #error missing atomic implementation for this compiler +#endif + +#if defined(CONF_PLATFORM_MACOSX) + /* + use semaphore provided by SDL on macosx + */ +#else + class semaphore + { + SEMAPHORE sem; + public: + semaphore() { semaphore_init(&sem); } + ~semaphore() { semaphore_destroy(&sem); } + void wait() { semaphore_wait(&sem); } + void signal() { semaphore_signal(&sem); } + }; +#endif + +class lock +{ + friend class scope_lock; + + LOCK var; + + void take() { lock_wait(var); } + void release() { lock_unlock(var); } + +public: + lock() + { + var = lock_create(); + } + + ~lock() + { + lock_destroy(var); + } +}; + +class scope_lock +{ + lock *var; +public: + scope_lock(lock *l) + { + var = l; + var->take(); + } + + ~scope_lock() + { + var->release(); + } +}; + +#endif // BASE_TL_THREADING_H diff --git a/src/base/vmath.h b/src/base/vmath.h new file mode 100644 index 000000000..300189ad3 --- /dev/null +++ b/src/base/vmath.h @@ -0,0 +1,224 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_VMATH_H +#define BASE_VMATH_H + +#include + +#include "math.h" // mix + +// ------------------------------------ + +template +class vector2_base +{ +public: + union { T x,u; }; + union { T y,v; }; + + vector2_base() {} + vector2_base(T nx, T ny) + { + x = nx; + y = ny; + } + + vector2_base operator -() const { return vector2_base(-x, -y); } + vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); } + vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); } + vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); } + vector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); } + vector2_base operator /(const T v) const { return vector2_base(x/v, y/v); } + vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); } + + const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; } + const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; } + const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this; } + const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; } + const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this; } + const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; } + + bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead + bool operator !=(const vector2_base &v) const { return x != v.x || y != v.y; } + + operator const T* () { return &x; } +}; + +template +inline vector2_base rotate(const vector2_base &a, float angle) +{ + angle = angle * pi / 180.0f; + float s = sinf(angle); + float c = cosf(angle); + return vector2_base((T)(c*a.x - s*a.y), (T)(s*a.x + c*a.y)); +} + +template +inline T distance(const vector2_base &a, const vector2_base &b) +{ + return length(a - b); +} + +template +inline T dot(const vector2_base &a, const vector2_base &b) +{ + return a.x*b.x + a.y*b.y; +} + +template +inline vector2_base closest_point_on_line(vector2_base line_point0, vector2_base line_point1, vector2_base target_point) +{ + vector2_base c = target_point - line_point0; + vector2_base v = line_point1 - line_point0; + v = normalize(v); + T d = length(line_point0 - line_point1); + T t = dot(v, c)/d; + return mix(line_point0, line_point1, clamp(t, (T)0, (T)1)); +} + +// +inline float length(const vector2_base &a) +{ + return sqrtf(dot(a, a)); +} + +inline float angle(const vector2_base &a) +{ + return atan2f(a.y, a.x); +} + +inline vector2_base normalize(const vector2_base &v) +{ + return v / length(v); +} + +inline vector2_base direction(float angle) +{ + return vector2_base(cosf(angle), sinf(angle)); +} + +typedef vector2_base vec2; +typedef vector2_base bvec2; +typedef vector2_base ivec2; + + +// ------------------------------------ +template +class vector3_base +{ +public: + union { T x,r,h; }; + union { T y,g,s; }; + union { T z,b,v,l; }; + + vector3_base() {} + vector3_base(T nx, T ny, T nz) + { + x = nx; + y = ny; + z = nz; + } + + vector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); } + vector3_base operator -() const { return vector3_base(-x, -y, -z); } + vector3_base operator +(const vector3_base &v) const { return vector3_base(x+v.x, y+v.y, z+v.z); } + vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); } + vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); } + vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); } + vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); } + + const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; } + const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } + const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this; } + const vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } + const vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this; } + const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } + + bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead + bool operator !=(const vector3_base &v) const { return x != v.x || y != v.y || z != v.z; } + + operator const T* () { return &x; } +}; + +template +inline T distance(const vector3_base &a, const vector3_base &b) +{ + return length(a - b); +} + +template +inline T dot(const vector3_base &a, const vector3_base &b) +{ + return a.x*b.x + a.y*b.y + a.z*b.z; +} + +template +inline vector3_base cross(const vector3_base &a, const vector3_base &b) +{ + return vector3_base( + a.y*b.z - a.z*b.y, + a.z*b.x - a.x*b.z, + a.x*b.y - a.y*b.x); +} + +// +inline float length(const vector3_base &a) +{ + return sqrtf(dot(a, a)); +} + +inline vector3_base normalize(const vector3_base &v) +{ + return v / length(v); +} + +typedef vector3_base vec3; +typedef vector3_base bvec3; +typedef vector3_base ivec3; + +// ------------------------------------ + +template +class vector4_base +{ +public: + union { T x,r; }; + union { T y,g; }; + union { T z,b; }; + union { T w,a; }; + + vector4_base() {} + vector4_base(T nx, T ny, T nz, T nw) + { + x = nx; + y = ny; + z = nz; + w = nw; + } + + vector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); } + vector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); } + vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); } + vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); } + vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); } + vector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); } + vector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); } + + const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } + const vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } + const vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this; } + const vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } + const vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this; } + const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } + + bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead + bool operator !=(const vector4_base &v) const { return x != v.x || y != v.y || z != v.z || w != v.w; } + + operator const T* () { return &x; } +}; + +typedef vector4_base vec4; +typedef vector4_base bvec4; +typedef vector4_base ivec4; + +#endif diff --git a/src/engine/config.h b/src/engine/config.h new file mode 100644 index 000000000..0e106abb4 --- /dev/null +++ b/src/engine/config.h @@ -0,0 +1,27 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CONFIG_H +#define ENGINE_CONFIG_H + +#include "kernel.h" + +class IConfigManager : public IInterface +{ + MACRO_INTERFACE("config", 0) +public: + typedef void (*SAVECALLBACKFUNC)(IConfigManager *pConfigManager, void *pUserData); + + virtual void Init(int FlagMask) = 0; + virtual void Reset() = 0; + virtual void RestoreStrings() = 0; + virtual void Save(const char *pFilename=0) = 0; + virtual class CConfig *Values() = 0; + + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) = 0; + + virtual void WriteLine(const char *pLine) = 0; +}; + +extern IConfigManager *CreateConfigManager(); + +#endif diff --git a/src/engine/console.h b/src/engine/console.h new file mode 100644 index 000000000..a0147f403 --- /dev/null +++ b/src/engine/console.h @@ -0,0 +1,108 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CONSOLE_H +#define ENGINE_CONSOLE_H + +#include "kernel.h" + +class IConsole : public IInterface +{ + MACRO_INTERFACE("console", 0) +public: + + // TODO: rework/cleanup + enum + { + OUTPUT_LEVEL_STANDARD=0, + OUTPUT_LEVEL_ADDINFO, + OUTPUT_LEVEL_DEBUG, + + ACCESS_LEVEL_ADMIN=0, + ACCESS_LEVEL_MOD, + + TEMPCMD_NAME_LENGTH=48, + TEMPCMD_HELP_LENGTH=128, + TEMPCMD_PARAMS_LENGTH=96, + + TEMPMAP_NAME_LENGTH = 32, + + MAX_PRINT_CB=4, + }; + + // TODO: rework this interface to reduce the amount of virtual calls + class IResult + { + protected: + unsigned m_NumArgs; + public: + int m_Value; + char m_aValue[128]; + IResult() { m_NumArgs = 0; } + virtual ~IResult() {} + + virtual int GetInteger(unsigned Index) = 0; + virtual float GetFloat(unsigned Index) = 0; + virtual const char *GetString(unsigned Index) = 0; + + int NumArguments() const { return m_NumArgs; } + }; + + class CCommandInfo + { + protected: + int m_AccessLevel; + public: + CCommandInfo(bool BasicAccess) { m_AccessLevel = BasicAccess ? ACCESS_LEVEL_MOD : ACCESS_LEVEL_ADMIN; } + virtual ~CCommandInfo() {} + const char *m_pName; + const char *m_pHelp; + const char *m_pParams; + + virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const = 0; + + int GetAccessLevel() const { return m_AccessLevel; } + }; + + typedef void (*FPrintCallback)(const char *pStr, void *pUser, bool Highlighted); + typedef void (*FPossibleCallback)(int Index, const char *pCmd, void *pUser); + typedef void (*FCommandCallback)(IResult *pResult, void *pUserData); + typedef void (*FChainCommandCallback)(IResult *pResult, void *pUserData, FCommandCallback pfnCallback, void *pCallbackUserData); + + static void EmptyPossibleCommandCallback(int Index, const char *pCmd, void *pUser) {} + + virtual void Init() = 0; + virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int Flagmask) const = 0; + virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp) = 0; + virtual int PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback = EmptyPossibleCommandCallback, void *pUser = 0) = 0; + virtual int PossibleMaps(const char *pStr, FPossibleCallback pfnCallback = EmptyPossibleCommandCallback, void *pUser = 0) = 0; + virtual void ParseArguments(int NumArgs, const char **ppArguments) = 0; + + virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) = 0; + virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) = 0; + virtual void DeregisterTemp(const char *pName) = 0; + virtual void DeregisterTempAll() = 0; + virtual void RegisterTempMap(const char *pName) = 0; + virtual void DeregisterTempMap(const char *pName) = 0; + virtual void DeregisterTempMapAll() = 0; + virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) = 0; + virtual void StoreCommands(bool Store) = 0; + + virtual bool ArgStringIsValid(const char *pFormat) = 0; + virtual bool LineIsValid(const char *pStr) = 0; + virtual void ExecuteLine(const char *pStr) = 0; + virtual void ExecuteLineFlag(const char *pStr, int FlagMask) = 0; + virtual void ExecuteLineStroked(int Stroke, const char *pStr) = 0; + virtual bool ExecuteFile(const char *pFilename) = 0; + + virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) = 0; + virtual void SetPrintOutputLevel(int Index, int OutputLevel) = 0; + virtual void Print(int Level, const char *pFrom, const char *pStr, bool Highlighted=false) = 0; + + virtual int ParseCommandArgs(const char *pArgs, const char *pFormat, FCommandCallback pfnCallback, void *pContext) = 0; + + virtual void SetAccessLevel(int AccessLevel) = 0; +}; + +extern IConsole *CreateConsole(int FlagMask); + +#endif // FILE_ENGINE_CONSOLE_H diff --git a/src/engine/contacts.h b/src/engine/contacts.h new file mode 100644 index 000000000..0adaea57d --- /dev/null +++ b/src/engine/contacts.h @@ -0,0 +1,55 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CONTACTS_H +#define ENGINE_CONTACTS_H + +#include + +#include "kernel.h" + +struct CContactInfo +{ + char m_aName[MAX_NAME_ARRAY_SIZE]; + char m_aClan[MAX_CLAN_ARRAY_SIZE]; + unsigned m_NameHash; + unsigned m_ClanHash; + + enum + { + // for contact lists + CONTACT_NO=0, + CONTACT_CLAN, + CONTACT_PLAYER, + + MAX_CONTACTS=128, + }; +}; + +class IFriends : public IInterface +{ + MACRO_INTERFACE("friends", 0) +public: + virtual void Init() = 0; + + virtual int NumFriends() const = 0; + virtual const CContactInfo *GetFriend(int Index) const = 0; + virtual int GetFriendState(const char *pName, const char *pClan) const = 0; + virtual bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const = 0; + + virtual void AddFriend(const char *pName, const char *pClan) = 0; + virtual void RemoveFriend(const char *pName, const char *pClan) = 0; +}; + +class IBlacklist : public IInterface +{ + MACRO_INTERFACE("blacklist", 0) +public: + virtual void Init() = 0; + + virtual bool IsIgnored(const char *pName, const char *pClan, bool PlayersOnly) const = 0; + + virtual void AddIgnoredPlayer(const char *pName, const char *pClan) = 0; + virtual void RemoveIgnoredPlayer(const char *pName, const char *pClan) = 0; +}; + +#endif diff --git a/src/engine/demo.h b/src/engine/demo.h new file mode 100644 index 000000000..cfe648cbc --- /dev/null +++ b/src/engine/demo.h @@ -0,0 +1,75 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_DEMO_H +#define ENGINE_DEMO_H + +#include "kernel.h" + +enum +{ + MAX_TIMELINE_MARKERS=64 +}; + +struct CDemoHeader +{ + unsigned char m_aMarker[7]; + unsigned char m_Version; + char m_aNetversion[64]; + char m_aMapName[64]; + unsigned char m_aMapSize[4]; + unsigned char m_aMapCrc[4]; + char m_aType[8]; + unsigned char m_aLength[4]; + char m_aTimestamp[20]; + unsigned char m_aNumTimelineMarkers[4]; + unsigned char m_aTimelineMarkers[MAX_TIMELINE_MARKERS][4]; +}; + +class IDemoPlayer : public IInterface +{ + MACRO_INTERFACE("demoplayer", 0) +public: + class CInfo + { + public: + bool m_Paused; + float m_Speed; + + int m_FirstTick; + int m_CurrentTick; + int m_LastTick; + + int m_NumTimelineMarkers; + int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; + }; + + enum + { + DEMOTYPE_INVALID=0, + DEMOTYPE_CLIENT, + DEMOTYPE_SERVER, + }; + + ~IDemoPlayer() {} + virtual void SetSpeed(float Speed) = 0; + virtual int SetPos(float Percent) = 0; + virtual int SetPos(int WantedTick) = 0; + virtual void Pause() = 0; + virtual void Unpause() = 0; + virtual const CInfo *BaseInfo() const = 0; + virtual void GetDemoName(char *pBuffer, int BufferSize) const = 0; + virtual bool GetDemoInfo(const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const = 0; + virtual int GetDemoType() const = 0; +}; + +class IDemoRecorder : public IInterface +{ + MACRO_INTERFACE("demorecorder", 0) +public: + ~IDemoRecorder() {} + virtual bool IsRecording() const = 0; + virtual int Stop() = 0; + virtual int Length() const = 0; +}; + +#endif diff --git a/src/engine/docs/client_time.txt b/src/engine/docs/client_time.txt new file mode 100644 index 000000000..0d4dd53e0 --- /dev/null +++ b/src/engine/docs/client_time.txt @@ -0,0 +1,11 @@ +Title: Time on the client + +tick, intratick +predtick, predintratick + + prevtick tick predtick + 4 8 14 + |---------------------|---------------------| + 0 <- intratick -> 1 + 0 <- ticktime(in s)-> X + 0 <- predintratick?-> 1 diff --git a/src/engine/docs/prediction.txt b/src/engine/docs/prediction.txt new file mode 100644 index 000000000..637c55969 --- /dev/null +++ b/src/engine/docs/prediction.txt @@ -0,0 +1,19 @@ +Title: Prediction + +The engine calls when reprediction is required. This happens usally when new data has arrived from the server. should to prediction from the current snapshot and current snapshot tick ( + 1) upto and including the tick returned by . + +Predicted input sent to the server can be retrieved by calling with the corresponding tick that you want the input for. Here is a simple example of how it might look. + +> void modc_predict() +> { +> int tick; +> prediction_reset(); +> +> for(tick = client_tick()+1; tick <= client_predtick(); tick++) +> { +> MY_INPUT *input = (MY_INPUT *)client_get_input(); +> if(input) +> prediction_apply_input(input); +> prediction_tick(); +> } +> } diff --git a/src/engine/docs/server_op.txt b/src/engine/docs/server_op.txt new file mode 100644 index 000000000..c0a054c48 --- /dev/null +++ b/src/engine/docs/server_op.txt @@ -0,0 +1,39 @@ +Title: Server Operation + +Section: Init + +Section: Running + +Here is an graph over how the server operates on each refresh. + +(start code) +load map +init mod + +while running + if map change then + load new map + shutdown mod + reset clients to init state + init mod + end if + + if new tick then + call + for each client do + create snapshot + send snapshot + end for + end + + process new network messages +end while + +unload map +(end) + + + +Section: Reinit + +Section: Shutdown diff --git a/src/engine/docs/snapshots.txt b/src/engine/docs/snapshots.txt new file mode 100644 index 000000000..35dd58520 --- /dev/null +++ b/src/engine/docs/snapshots.txt @@ -0,0 +1,58 @@ +Title: Snapshots + +Section: Overview + +Topic: Definitions + +- *Snapshot*. A is a serialized game state from which a client can render the game from. They are sent from the server at a regular interval and is created specifically for each client in order to reduce bandwidth. +- *Delta Snapshot*. A set of data that can be applied to a snapshot in order to create a new snapshot with the updated game state. + +Topic: Structure + +A snapshot contains a series of items. Each item have a type, id and data. + +- *Type*. Type of item. Could be projectile or character for example. +- *Id*. A unique id so the client can identify the item between two snapshots. +- *Data*. A series of 32-bit integers that contains the per item type specific data. + +Section: Server Side + +Topic: Creating + +Items can be added when is called using the function to insert an item to the snapshot. The server can not inspect the snapshot that is in progress of being created. + +Section: Client Side + +Topic: Inspection + is called when a new snapshot has arrived for processing. , and can be used to inspect the current and previous snapshot. This can be done anywhere while the client is running and not just in the function. The client can also call if an item contains improper information that could harm the operation of the client. This should however be done in to assure that no bad data propagates into the rest of the client. + +Topic: Rendering +DOCTODO + +Section: In depth + +Topic: Compression + +After a snapshot have been created, compression is applied to reduce the bandwidth. There are several steps taken in order to reduce the size of the snapshot. + +- *Delta*. The server looks in a clients backlog of snapshots to find a previous acked snapshot. It then compares the two snapshots and creates a delta snapshot containing the changes from the previous acked snapshot to the new one. +- *Variable Integers*. The delta snapshot which is only consisting of 32-bit integers is then encoded into variable integers similar to UTF-8. Each byte has a bit that tells the decoder that it needs one more byte to decode the 32-bit integer. The first byte also contains a bit for telling the sign of the integer. + +> ESDDDDDD EDDDDDDD EDDDDDDD EDDDDDDD + +> E = extend +> S = sign +> D = data bit + +- *Huffman*. The last step is to compress the buffer with a huffman encoder. It uses a static tree that is weighted towards 0 because it's where most of the data will be because of the delta compression. + +Topic: Interval + +The interval for how often a client receives a snapshot changes during the course of the connection. There are three different snapshot rates. + +- *Init*. 5 snapshots per second. Used when a client is connecting and used until the client has acknowledged a snapshot. This mechanism is used because delta compression can not be applied to the first snapshot. + +- *Full*. Snapshot for every tick or every even tick depending on server configuration. This is used during normal gameplay and everything is running smooth. + +- *Recovery*. 1 snapshot each second. A client enters recovery rate when it haven't acknowledged a snapshot over 1 second. This is to let the client to be able to recover if it has a slow connection. + diff --git a/src/engine/engine.h b/src/engine/engine.h new file mode 100644 index 000000000..9b6217f5a --- /dev/null +++ b/src/engine/engine.h @@ -0,0 +1,36 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_ENGINE_H +#define ENGINE_ENGINE_H + +#include "kernel.h" +#include + +class CHostLookup +{ +public: + CJob m_Job; + char m_aHostname[128]; + int m_Nettype; + NETADDR m_Addr; +}; + +class IEngine : public IInterface +{ + MACRO_INTERFACE("engine", 0) + +protected: + class CJobPool m_JobPool; + +public: + virtual void Init() = 0; + virtual void ShutdownJobs() = 0; + virtual void InitLogfile() = 0; + virtual void QueryNetLogHandles(IOHANDLE *pHDLSend, IOHANDLE *pHDLRecv) = 0; + virtual void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) = 0; + virtual void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) = 0; +}; + +extern IEngine *CreateEngine(const char *pAppname); + +#endif diff --git a/src/engine/external/important.txt b/src/engine/external/important.txt new file mode 100644 index 000000000..41b9c6a11 --- /dev/null +++ b/src/engine/external/important.txt @@ -0,0 +1,5 @@ +The source code under this directory are external libraries +with their own licences. The source you find here is stripped +of unnecessary information. Please visit their websites for +more information and official releases. + diff --git a/src/engine/external/json-parser/VERSION.txt b/src/engine/external/json-parser/VERSION.txt new file mode 100644 index 000000000..5e5c4eec9 --- /dev/null +++ b/src/engine/external/json-parser/VERSION.txt @@ -0,0 +1 @@ +unmarked version: 11.11.2018 diff --git a/src/engine/external/json-parser/json.c b/src/engine/external/json-parser/json.c new file mode 100644 index 000000000..c44b84e5a --- /dev/null +++ b/src/engine/external/json-parser/json.c @@ -0,0 +1,1011 @@ +/* vim: set et ts=3 sw=3 sts=3 ft=c: + * + * Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved. + * https://github.com/udp/json-parser + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "json.h" + +#ifdef _MSC_VER + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif +#endif + +const struct _json_value json_value_none; + +#include +#include +#include +#include + +typedef unsigned int json_uchar; + +static unsigned char hex_value (json_char c) +{ + if (isdigit(c)) + return c - '0'; + + switch (c) { + case 'a': case 'A': return 0x0A; + case 'b': case 'B': return 0x0B; + case 'c': case 'C': return 0x0C; + case 'd': case 'D': return 0x0D; + case 'e': case 'E': return 0x0E; + case 'f': case 'F': return 0x0F; + default: return 0xFF; + } +} + +typedef struct +{ + unsigned long used_memory; + + unsigned int uint_max; + unsigned long ulong_max; + + json_settings settings; + int first_pass; + + const json_char * ptr; + unsigned int cur_line, cur_col; + +} json_state; + +static void * default_alloc (size_t size, int zero, void * user_data) +{ + return zero ? calloc (1, size) : malloc (size); +} + +static void default_free (void * ptr, void * user_data) +{ + free (ptr); +} + +static void * json_alloc (json_state * state, unsigned long size, int zero) +{ + if ((state->ulong_max - state->used_memory) < size) + return 0; + + if (state->settings.max_memory + && (state->used_memory += size) > state->settings.max_memory) + { + return 0; + } + + return state->settings.mem_alloc (size, zero, state->settings.user_data); +} + +static int new_value (json_state * state, + json_value ** top, json_value ** root, json_value ** alloc, + json_type type) +{ + json_value * value; + int values_size; + + if (!state->first_pass) + { + value = *top = *alloc; + *alloc = (*alloc)->_reserved.next_alloc; + + if (!*root) + *root = value; + + switch (value->type) + { + case json_array: + + if (value->u.array.length == 0) + break; + + if (! (value->u.array.values = (json_value **) json_alloc + (state, value->u.array.length * sizeof (json_value *), 0)) ) + { + return 0; + } + + value->u.array.length = 0; + break; + + case json_object: + + if (value->u.object.length == 0) + break; + + values_size = sizeof (*value->u.object.values) * value->u.object.length; + + if (! (value->u.object.values = (json_object_entry *) json_alloc + (state, values_size + ((unsigned long) value->u.object.values), 0)) ) + { + return 0; + } + + value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size; + + value->u.object.length = 0; + break; + + case json_string: + + if (! (value->u.string.ptr = (json_char *) json_alloc + (state, (value->u.string.length + 1) * sizeof (json_char), 0)) ) + { + return 0; + } + + value->u.string.length = 0; + break; + + default: + break; + }; + + return 1; + } + + if (! (value = (json_value *) json_alloc + (state, sizeof (json_value) + state->settings.value_extra, 1))) + { + return 0; + } + + if (!*root) + *root = value; + + value->type = type; + value->parent = *top; + + #ifdef JSON_TRACK_SOURCE + value->line = state->cur_line; + value->col = state->cur_col; + #endif + + if (*alloc) + (*alloc)->_reserved.next_alloc = value; + + *alloc = *top = value; + + return 1; +} + +#define whitespace \ + case '\n': ++ state.cur_line; state.cur_col = 0; \ + case ' ': case '\t': case '\r' + +#define string_add(b) \ + do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0); + +#define line_and_col \ + state.cur_line, state.cur_col + +static const long + flag_next = 1 << 0, + flag_reproc = 1 << 1, + flag_need_comma = 1 << 2, + flag_seek_value = 1 << 3, + flag_escaped = 1 << 4, + flag_string = 1 << 5, + flag_need_colon = 1 << 6, + flag_done = 1 << 7, + flag_num_negative = 1 << 8, + flag_num_zero = 1 << 9, + flag_num_e = 1 << 10, + flag_num_e_got_sign = 1 << 11, + flag_num_e_negative = 1 << 12, + flag_line_comment = 1 << 13, + flag_block_comment = 1 << 14; + +json_value * json_parse_ex (json_settings * settings, + const json_char * json, + size_t length, + char * error_buf) +{ + json_char error [json_error_max]; + const json_char * end; + json_value * top, * root, * alloc = 0; + json_state state = { 0 }; + long flags; + long num_digits = 0, num_e = 0; + json_int_t num_fraction = 0; + + /* Skip UTF-8 BOM + */ + if (length >= 3 && ((unsigned char) json [0]) == 0xEF + && ((unsigned char) json [1]) == 0xBB + && ((unsigned char) json [2]) == 0xBF) + { + json += 3; + length -= 3; + } + + error[0] = '\0'; + end = (json + length); + + memcpy (&state.settings, settings, sizeof (json_settings)); + + if (!state.settings.mem_alloc) + state.settings.mem_alloc = default_alloc; + + if (!state.settings.mem_free) + state.settings.mem_free = default_free; + + memset (&state.uint_max, 0xFF, sizeof (state.uint_max)); + memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max)); + + state.uint_max -= 8; /* limit of how much can be added before next check */ + state.ulong_max -= 8; + + for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass) + { + json_uchar uchar; + unsigned char uc_b1, uc_b2, uc_b3, uc_b4; + json_char * string = 0; + unsigned int string_length = 0; + + top = root = 0; + flags = flag_seek_value; + + state.cur_line = 1; + + for (state.ptr = json ;; ++ state.ptr) + { + json_char b = (state.ptr == end ? 0 : *state.ptr); + + if (flags & flag_string) + { + if (!b) + { sprintf (error, "Unexpected EOF in string (at %d:%d)", line_and_col); + goto e_failed; + } + + if (string_length > state.uint_max) + goto e_overflow; + + if (flags & flag_escaped) + { + flags &= ~ flag_escaped; + + switch (b) + { + case 'b': string_add ('\b'); break; + case 'f': string_add ('\f'); break; + case 'n': string_add ('\n'); break; + case 'r': string_add ('\r'); break; + case 't': string_add ('\t'); break; + case 'u': + + if (end - state.ptr <= 4 || + (uc_b1 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b2 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b3 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b4 = hex_value (*++ state.ptr)) == 0xFF) + { + sprintf (error, "Invalid character value `%c` (at %d:%d)", b, line_and_col); + goto e_failed; + } + + uc_b1 = (uc_b1 << 4) | uc_b2; + uc_b2 = (uc_b3 << 4) | uc_b4; + uchar = (uc_b1 << 8) | uc_b2; + + if ((uchar & 0xF800) == 0xD800) { + json_uchar uchar2; + + if (end - state.ptr <= 6 || (*++ state.ptr) != '\\' || (*++ state.ptr) != 'u' || + (uc_b1 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b2 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b3 = hex_value (*++ state.ptr)) == 0xFF || + (uc_b4 = hex_value (*++ state.ptr)) == 0xFF) + { + sprintf (error, "Invalid character value `%c` (at %d:%d)", b, line_and_col); + goto e_failed; + } + + uc_b1 = (uc_b1 << 4) | uc_b2; + uc_b2 = (uc_b3 << 4) | uc_b4; + uchar2 = (uc_b1 << 8) | uc_b2; + + uchar = 0x010000 | ((uchar & 0x3FF) << 10) | (uchar2 & 0x3FF); + } + + if (sizeof (json_char) >= sizeof (json_uchar) || (uchar <= 0x7F)) + { + string_add ((json_char) uchar); + break; + } + + if (uchar <= 0x7FF) + { + if (state.first_pass) + string_length += 2; + else + { string [string_length ++] = 0xC0 | (uchar >> 6); + string [string_length ++] = 0x80 | (uchar & 0x3F); + } + + break; + } + + if (uchar <= 0xFFFF) { + if (state.first_pass) + string_length += 3; + else + { string [string_length ++] = 0xE0 | (uchar >> 12); + string [string_length ++] = 0x80 | ((uchar >> 6) & 0x3F); + string [string_length ++] = 0x80 | (uchar & 0x3F); + } + + break; + } + + if (state.first_pass) + string_length += 4; + else + { string [string_length ++] = 0xF0 | (uchar >> 18); + string [string_length ++] = 0x80 | ((uchar >> 12) & 0x3F); + string [string_length ++] = 0x80 | ((uchar >> 6) & 0x3F); + string [string_length ++] = 0x80 | (uchar & 0x3F); + } + + break; + + default: + string_add (b); + }; + + continue; + } + + if (b == '\\') + { + flags |= flag_escaped; + continue; + } + + if (b == '"') + { + if (!state.first_pass) + string [string_length] = 0; + + flags &= ~ flag_string; + string = 0; + + switch (top->type) + { + case json_string: + + top->u.string.length = string_length; + flags |= flag_next; + + break; + + case json_object: + + if (state.first_pass) + (*(json_char **) &top->u.object.values) += string_length + 1; + else + { + top->u.object.values [top->u.object.length].name + = (json_char *) top->_reserved.object_mem; + + top->u.object.values [top->u.object.length].name_length + = string_length; + + (*(json_char **) &top->_reserved.object_mem) += string_length + 1; + } + + flags |= flag_seek_value | flag_need_colon; + continue; + + default: + break; + }; + } + else + { + string_add (b); + continue; + } + } + + if (state.settings.settings & json_enable_comments) + { + if (flags & (flag_line_comment | flag_block_comment)) + { + if (flags & flag_line_comment) + { + if (b == '\r' || b == '\n' || !b) + { + flags &= ~ flag_line_comment; + -- state.ptr; /* so null can be reproc'd */ + } + + continue; + } + + if (flags & flag_block_comment) + { + if (!b) + { sprintf (error, "%d:%d: Unexpected EOF in block comment", line_and_col); + goto e_failed; + } + + if (b == '*' && state.ptr < (end - 1) && state.ptr [1] == '/') + { + flags &= ~ flag_block_comment; + ++ state.ptr; /* skip closing sequence */ + } + + continue; + } + } + else if (b == '/') + { + if (! (flags & (flag_seek_value | flag_done)) && top->type != json_object) + { sprintf (error, "%d:%d: Comment not allowed here", line_and_col); + goto e_failed; + } + + if (++ state.ptr == end) + { sprintf (error, "%d:%d: EOF unexpected", line_and_col); + goto e_failed; + } + + switch (b = *state.ptr) + { + case '/': + flags |= flag_line_comment; + continue; + + case '*': + flags |= flag_block_comment; + continue; + + default: + sprintf (error, "%d:%d: Unexpected `%c` in comment opening sequence", line_and_col, b); + goto e_failed; + }; + } + } + + if (flags & flag_done) + { + if (!b) + break; + + switch (b) + { + whitespace: + continue; + + default: + + sprintf (error, "%d:%d: Trailing garbage: `%c`", + state.cur_line, state.cur_col, b); + + goto e_failed; + }; + } + + if (flags & flag_seek_value) + { + switch (b) + { + whitespace: + continue; + + case ']': + + if (top && top->type == json_array) + flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next; + else + { sprintf (error, "%d:%d: Unexpected ]", line_and_col); + goto e_failed; + } + + break; + + default: + + if (flags & flag_need_comma) + { + if (b == ',') + { flags &= ~ flag_need_comma; + continue; + } + else + { + sprintf (error, "%d:%d: Expected , before %c", + state.cur_line, state.cur_col, b); + + goto e_failed; + } + } + + if (flags & flag_need_colon) + { + if (b == ':') + { flags &= ~ flag_need_colon; + continue; + } + else + { + sprintf (error, "%d:%d: Expected : before %c", + state.cur_line, state.cur_col, b); + + goto e_failed; + } + } + + flags &= ~ flag_seek_value; + + switch (b) + { + case '{': + + if (!new_value (&state, &top, &root, &alloc, json_object)) + goto e_alloc_failure; + + continue; + + case '[': + + if (!new_value (&state, &top, &root, &alloc, json_array)) + goto e_alloc_failure; + + flags |= flag_seek_value; + continue; + + case '"': + + if (!new_value (&state, &top, &root, &alloc, json_string)) + goto e_alloc_failure; + + flags |= flag_string; + + string = top->u.string.ptr; + string_length = 0; + + continue; + + case 't': + + if ((end - state.ptr) < 3 || *(++ state.ptr) != 'r' || + *(++ state.ptr) != 'u' || *(++ state.ptr) != 'e') + { + goto e_unknown_value; + } + + if (!new_value (&state, &top, &root, &alloc, json_boolean)) + goto e_alloc_failure; + + top->u.boolean = 1; + + flags |= flag_next; + break; + + case 'f': + + if ((end - state.ptr) < 4 || *(++ state.ptr) != 'a' || + *(++ state.ptr) != 'l' || *(++ state.ptr) != 's' || + *(++ state.ptr) != 'e') + { + goto e_unknown_value; + } + + if (!new_value (&state, &top, &root, &alloc, json_boolean)) + goto e_alloc_failure; + + flags |= flag_next; + break; + + case 'n': + + if ((end - state.ptr) < 3 || *(++ state.ptr) != 'u' || + *(++ state.ptr) != 'l' || *(++ state.ptr) != 'l') + { + goto e_unknown_value; + } + + if (!new_value (&state, &top, &root, &alloc, json_null)) + goto e_alloc_failure; + + flags |= flag_next; + break; + + default: + + if (isdigit (b) || b == '-') + { + if (!new_value (&state, &top, &root, &alloc, json_integer)) + goto e_alloc_failure; + + if (!state.first_pass) + { + while (isdigit (b) || b == '+' || b == '-' + || b == 'e' || b == 'E' || b == '.') + { + if ( (++ state.ptr) == end) + { + b = 0; + break; + } + + b = *state.ptr; + } + + flags |= flag_next | flag_reproc; + break; + } + + flags &= ~ (flag_num_negative | flag_num_e | + flag_num_e_got_sign | flag_num_e_negative | + flag_num_zero); + + num_digits = 0; + num_fraction = 0; + num_e = 0; + + if (b != '-') + { + flags |= flag_reproc; + break; + } + + flags |= flag_num_negative; + continue; + } + else + { sprintf (error, "%d:%d: Unexpected %c when seeking value", line_and_col, b); + goto e_failed; + } + }; + }; + } + else + { + switch (top->type) + { + case json_object: + + switch (b) + { + whitespace: + continue; + + case '"': + + if (flags & flag_need_comma) + { sprintf (error, "%d:%d: Expected , before \"", line_and_col); + goto e_failed; + } + + flags |= flag_string; + + string = (json_char *) top->_reserved.object_mem; + string_length = 0; + + break; + + case '}': + + flags = (flags & ~ flag_need_comma) | flag_next; + break; + + case ',': + + if (flags & flag_need_comma) + { + flags &= ~ flag_need_comma; + break; + } + + default: + sprintf (error, "%d:%d: Unexpected `%c` in object", line_and_col, b); + goto e_failed; + }; + + break; + + case json_integer: + case json_double: + + if (isdigit (b)) + { + ++ num_digits; + + if (top->type == json_integer || flags & flag_num_e) + { + if (! (flags & flag_num_e)) + { + if (flags & flag_num_zero) + { sprintf (error, "%d:%d: Unexpected `0` before `%c`", line_and_col, b); + goto e_failed; + } + + if (num_digits == 1 && b == '0') + flags |= flag_num_zero; + } + else + { + flags |= flag_num_e_got_sign; + num_e = (num_e * 10) + (b - '0'); + continue; + } + + top->u.integer = (top->u.integer * 10) + (b - '0'); + continue; + } + + num_fraction = (num_fraction * 10) + (b - '0'); + continue; + } + + if (b == '+' || b == '-') + { + if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign)) + { + flags |= flag_num_e_got_sign; + + if (b == '-') + flags |= flag_num_e_negative; + + continue; + } + } + else if (b == '.' && top->type == json_integer) + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit before `.`", line_and_col); + goto e_failed; + } + + top->type = json_double; + top->u.dbl = (double) top->u.integer; + + num_digits = 0; + continue; + } + + if (! (flags & flag_num_e)) + { + if (top->type == json_double) + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit after `.`", line_and_col); + goto e_failed; + } + + top->u.dbl += ((double) num_fraction) / (pow (10.0, (double) num_digits)); + } + + if (b == 'e' || b == 'E') + { + flags |= flag_num_e; + + if (top->type == json_integer) + { + top->type = json_double; + top->u.dbl = (double) top->u.integer; + } + + num_digits = 0; + flags &= ~ flag_num_zero; + + continue; + } + } + else + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit after `e`", line_and_col); + goto e_failed; + } + + top->u.dbl *= pow (10.0, (double) + (flags & flag_num_e_negative ? - num_e : num_e)); + } + + if (flags & flag_num_negative) + { + if (top->type == json_integer) + top->u.integer = - top->u.integer; + else + top->u.dbl = - top->u.dbl; + } + + flags |= flag_next | flag_reproc; + break; + + default: + break; + }; + } + + if (flags & flag_reproc) + { + flags &= ~ flag_reproc; + -- state.ptr; + } + + if (flags & flag_next) + { + flags = (flags & ~ flag_next) | flag_need_comma; + + if (!top->parent) + { + /* root value done */ + + flags |= flag_done; + continue; + } + + if (top->parent->type == json_array) + flags |= flag_seek_value; + + if (!state.first_pass) + { + json_value * parent = top->parent; + + switch (parent->type) + { + case json_object: + + parent->u.object.values + [parent->u.object.length].value = top; + + break; + + case json_array: + + parent->u.array.values + [parent->u.array.length] = top; + + break; + + default: + break; + }; + } + + if ( (++ top->parent->u.array.length) > state.uint_max) + goto e_overflow; + + top = top->parent; + + continue; + } + } + + alloc = root; + } + + return root; + +e_unknown_value: + + sprintf (error, "%d:%d: Unknown value", line_and_col); + goto e_failed; + +e_alloc_failure: + + strcpy (error, "Memory allocation failure"); + goto e_failed; + +e_overflow: + + sprintf (error, "%d:%d: Too long (caught overflow)", line_and_col); + goto e_failed; + +e_failed: + + if (error_buf) + { + if (*error) + strcpy (error_buf, error); + else + strcpy (error_buf, "Unknown error"); + } + + if (state.first_pass) + alloc = root; + + while (alloc) + { + top = alloc->_reserved.next_alloc; + state.settings.mem_free (alloc, state.settings.user_data); + alloc = top; + } + + if (!state.first_pass) + json_value_free_ex (&state.settings, root); + + return 0; +} + +json_value * json_parse (const json_char * json, size_t length) +{ + json_settings settings = { 0 }; + return json_parse_ex (&settings, json, length, 0); +} + +void json_value_free_ex (json_settings * settings, json_value * value) +{ + json_value * cur_value; + + if (!value) + return; + + value->parent = 0; + + while (value) + { + switch (value->type) + { + case json_array: + + if (!value->u.array.length) + { + settings->mem_free (value->u.array.values, settings->user_data); + break; + } + + value = value->u.array.values [-- value->u.array.length]; + continue; + + case json_object: + + if (!value->u.object.length) + { + settings->mem_free (value->u.object.values, settings->user_data); + break; + } + + value = value->u.object.values [-- value->u.object.length].value; + continue; + + case json_string: + + settings->mem_free (value->u.string.ptr, settings->user_data); + break; + + default: + break; + }; + + cur_value = value; + value = value->parent; + settings->mem_free (cur_value, settings->user_data); + } +} + +void json_value_free (json_value * value) +{ + json_settings settings = { 0 }; + settings.mem_free = default_free; + json_value_free_ex (&settings, value); +} + diff --git a/src/engine/external/json-parser/json.h b/src/engine/external/json-parser/json.h new file mode 100644 index 000000000..f6549ec4e --- /dev/null +++ b/src/engine/external/json-parser/json.h @@ -0,0 +1,283 @@ + +/* vim: set et ts=3 sw=3 sts=3 ft=c: + * + * Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved. + * https://github.com/udp/json-parser + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef _JSON_H +#define _JSON_H + +#ifndef json_char + #define json_char char +#endif + +#ifndef json_int_t + #ifndef _MSC_VER + #include + #define json_int_t int64_t + #else + #define json_int_t __int64 + #endif +#endif + +#include + +#ifdef __cplusplus + + #include + + extern "C" + { + +#endif + +typedef struct +{ + unsigned long max_memory; + int settings; + + /* Custom allocator support (leave null to use malloc/free) + */ + + void * (* mem_alloc) (size_t, int zero, void * user_data); + void (* mem_free) (void *, void * user_data); + + void * user_data; /* will be passed to mem_alloc and mem_free */ + + size_t value_extra; /* how much extra space to allocate for values? */ + +} json_settings; + +#define json_enable_comments 0x01 + +typedef enum +{ + json_none, + json_object, + json_array, + json_integer, + json_double, + json_string, + json_boolean, + json_null + +} json_type; + +extern const struct _json_value json_value_none; + +typedef struct _json_object_entry +{ + json_char * name; + unsigned int name_length; + + struct _json_value * value; + +} json_object_entry; + +typedef struct _json_value +{ + struct _json_value * parent; + + json_type type; + + union + { + int boolean; + json_int_t integer; + double dbl; + + struct + { + unsigned int length; + json_char * ptr; /* null terminated */ + + } string; + + struct + { + unsigned int length; + + json_object_entry * values; + + #if defined(__cplusplus) && __cplusplus >= 201103L + decltype(values) begin () const + { return values; + } + decltype(values) end () const + { return values + length; + } + #endif + + } object; + + struct + { + unsigned int length; + struct _json_value ** values; + + #if defined(__cplusplus) && __cplusplus >= 201103L + decltype(values) begin () const + { return values; + } + decltype(values) end () const + { return values + length; + } + #endif + + } array; + + } u; + + union + { + struct _json_value * next_alloc; + void * object_mem; + + } _reserved; + + #ifdef JSON_TRACK_SOURCE + + /* Location of the value in the source JSON + */ + unsigned int line, col; + + #endif + + + /* Some C++ operator sugar */ + + #ifdef __cplusplus + + public: + + inline _json_value () + { memset (this, 0, sizeof (_json_value)); + } + + inline const struct _json_value &operator [] (int index) const + { + if (type != json_array || index < 0 + || ((unsigned int) index) >= u.array.length) + { + return json_value_none; + } + + return *u.array.values [index]; + } + + inline const struct _json_value &operator [] (const char * index) const + { + if (type != json_object) + return json_value_none; + + for (unsigned int i = 0; i < u.object.length; ++ i) + if (!strcmp (u.object.values [i].name, index)) + return *u.object.values [i].value; + + return json_value_none; + } + + inline operator const char * () const + { + switch (type) + { + case json_string: + return u.string.ptr; + + default: + return ""; + }; + } + + inline operator json_int_t () const + { + switch (type) + { + case json_integer: + return u.integer; + + case json_double: + return (json_int_t) u.dbl; + + default: + return 0; + }; + } + + inline operator bool () const + { + if (type != json_boolean) + return false; + + return u.boolean != 0; + } + + inline operator double () const + { + switch (type) + { + case json_integer: + return (double) u.integer; + + case json_double: + return u.dbl; + + default: + return 0; + }; + } + + #endif + +} json_value; + +json_value * json_parse (const json_char * json, + size_t length); + +#define json_error_max 128 +json_value * json_parse_ex (json_settings * settings, + const json_char * json, + size_t length, + char * error); + +void json_value_free (json_value *); + + +/* Not usually necessary, unless you used a custom mem_alloc and now want to + * use a custom mem_free. + */ +void json_value_free_ex (json_settings * settings, + json_value *); + + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif + + diff --git a/src/engine/external/md5/md5.c b/src/engine/external/md5/md5.c new file mode 100644 index 000000000..99877cd7a --- /dev/null +++ b/src/engine/external/md5/md5.c @@ -0,0 +1,381 @@ +/* + Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + L. Peter Deutsch + ghost@aladdin.com + + */ +/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */ +/* + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.c is L. Peter Deutsch + . Other authors are noted in the change history + that follows (in reverse chronological order): + + 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order + either statically or dynamically; added missing #include + in library. + 2002-03-11 lpd Corrected argument list for main(), and added int return + type, in test program and T value program. + 2002-02-21 lpd Added missing #include in test program. + 2000-07-03 lpd Patched to eliminate warnings about "constant is + unsigned in ANSI C, signed in traditional"; made test program + self-checking. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). + 1999-05-03 lpd Original version. + */ + +#include "md5.h" +#include + +#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ +#ifdef ARCH_IS_BIG_ENDIAN +# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) +#else +# define BYTE_ORDER 0 +#endif + +#define T_MASK ((md5_word_t)~0) +#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) +#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) +#define T3 0x242070db +#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) +#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) +#define T6 0x4787c62a +#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) +#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) +#define T9 0x698098d8 +#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) +#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) +#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) +#define T13 0x6b901122 +#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) +#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) +#define T16 0x49b40821 +#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) +#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) +#define T19 0x265e5a51 +#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) +#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) +#define T22 0x02441453 +#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) +#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) +#define T25 0x21e1cde6 +#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) +#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) +#define T28 0x455a14ed +#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) +#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) +#define T31 0x676f02d9 +#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) +#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) +#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) +#define T35 0x6d9d6122 +#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) +#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) +#define T38 0x4bdecfa9 +#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) +#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) +#define T41 0x289b7ec6 +#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) +#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) +#define T44 0x04881d05 +#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) +#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) +#define T47 0x1fa27cf8 +#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) +#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) +#define T50 0x432aff97 +#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) +#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) +#define T53 0x655b59c3 +#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) +#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) +#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) +#define T57 0x6fa87e4f +#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) +#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) +#define T60 0x4e0811a1 +#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) +#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) +#define T63 0x2ad7d2bb +#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) + + +static void +md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) +{ + md5_word_t + a = pms->abcd[0], b = pms->abcd[1], + c = pms->abcd[2], d = pms->abcd[3]; + md5_word_t t; +#if BYTE_ORDER > 0 + /* Define storage only for big-endian CPUs. */ + md5_word_t X[16]; +#else + /* Define storage for little-endian or both types of CPUs. */ + md5_word_t xbuf[16]; + const md5_word_t *X; +#endif + + { +#if BYTE_ORDER == 0 + /* + * Determine dynamically whether this is a big-endian or + * little-endian machine, since we can use a more efficient + * algorithm on the latter. + */ + static const int w = 1; + + if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ +#endif +#if BYTE_ORDER <= 0 /* little-endian */ + { + /* + * On little-endian machines, we can process properly aligned + * data without copying it. + */ + if (!((data - (const md5_byte_t *)0) & 3)) { + /* data are properly aligned */ + X = (const md5_word_t *)data; + } else { + /* not aligned */ + memcpy(xbuf, data, 64); + X = xbuf; + } + } +#endif +#if BYTE_ORDER == 0 + else /* dynamic big-endian */ +#endif +#if BYTE_ORDER >= 0 /* big-endian */ + { + /* + * On big-endian machines, we must arrange the bytes in the + * right order. + */ + const md5_byte_t *xp = data; + int i; + +# if BYTE_ORDER == 0 + X = xbuf; /* (dynamic only) */ +# else +# define xbuf X /* (static only) */ +# endif + for (i = 0; i < 16; ++i, xp += 4) + xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); + } +#endif + } + +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + + /* Round 1. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ +#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + F(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 0, 7, T1); + SET(d, a, b, c, 1, 12, T2); + SET(c, d, a, b, 2, 17, T3); + SET(b, c, d, a, 3, 22, T4); + SET(a, b, c, d, 4, 7, T5); + SET(d, a, b, c, 5, 12, T6); + SET(c, d, a, b, 6, 17, T7); + SET(b, c, d, a, 7, 22, T8); + SET(a, b, c, d, 8, 7, T9); + SET(d, a, b, c, 9, 12, T10); + SET(c, d, a, b, 10, 17, T11); + SET(b, c, d, a, 11, 22, T12); + SET(a, b, c, d, 12, 7, T13); + SET(d, a, b, c, 13, 12, T14); + SET(c, d, a, b, 14, 17, T15); + SET(b, c, d, a, 15, 22, T16); +#undef SET + + /* Round 2. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ +#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + G(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 1, 5, T17); + SET(d, a, b, c, 6, 9, T18); + SET(c, d, a, b, 11, 14, T19); + SET(b, c, d, a, 0, 20, T20); + SET(a, b, c, d, 5, 5, T21); + SET(d, a, b, c, 10, 9, T22); + SET(c, d, a, b, 15, 14, T23); + SET(b, c, d, a, 4, 20, T24); + SET(a, b, c, d, 9, 5, T25); + SET(d, a, b, c, 14, 9, T26); + SET(c, d, a, b, 3, 14, T27); + SET(b, c, d, a, 8, 20, T28); + SET(a, b, c, d, 13, 5, T29); + SET(d, a, b, c, 2, 9, T30); + SET(c, d, a, b, 7, 14, T31); + SET(b, c, d, a, 12, 20, T32); +#undef SET + + /* Round 3. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + H(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 5, 4, T33); + SET(d, a, b, c, 8, 11, T34); + SET(c, d, a, b, 11, 16, T35); + SET(b, c, d, a, 14, 23, T36); + SET(a, b, c, d, 1, 4, T37); + SET(d, a, b, c, 4, 11, T38); + SET(c, d, a, b, 7, 16, T39); + SET(b, c, d, a, 10, 23, T40); + SET(a, b, c, d, 13, 4, T41); + SET(d, a, b, c, 0, 11, T42); + SET(c, d, a, b, 3, 16, T43); + SET(b, c, d, a, 6, 23, T44); + SET(a, b, c, d, 9, 4, T45); + SET(d, a, b, c, 12, 11, T46); + SET(c, d, a, b, 15, 16, T47); + SET(b, c, d, a, 2, 23, T48); +#undef SET + + /* Round 4. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ +#define I(x, y, z) ((y) ^ ((x) | ~(z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + I(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 0, 6, T49); + SET(d, a, b, c, 7, 10, T50); + SET(c, d, a, b, 14, 15, T51); + SET(b, c, d, a, 5, 21, T52); + SET(a, b, c, d, 12, 6, T53); + SET(d, a, b, c, 3, 10, T54); + SET(c, d, a, b, 10, 15, T55); + SET(b, c, d, a, 1, 21, T56); + SET(a, b, c, d, 8, 6, T57); + SET(d, a, b, c, 15, 10, T58); + SET(c, d, a, b, 6, 15, T59); + SET(b, c, d, a, 13, 21, T60); + SET(a, b, c, d, 4, 6, T61); + SET(d, a, b, c, 11, 10, T62); + SET(c, d, a, b, 2, 15, T63); + SET(b, c, d, a, 9, 21, T64); +#undef SET + + /* Then perform the following additions. (That is increment each + of the four registers by the value it had before this block + was started.) */ + pms->abcd[0] += a; + pms->abcd[1] += b; + pms->abcd[2] += c; + pms->abcd[3] += d; +} + +void +md5_init(md5_state_t *pms) +{ + pms->count[0] = pms->count[1] = 0; + pms->abcd[0] = 0x67452301; + pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; + pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; + pms->abcd[3] = 0x10325476; +} + +void +md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) +{ + const md5_byte_t *p = data; + int left = nbytes; + int offset = (pms->count[0] >> 3) & 63; + md5_word_t nbits = (md5_word_t)(nbytes << 3); + + if (nbytes <= 0) + return; + + /* Update the message length. */ + pms->count[1] += nbytes >> 29; + pms->count[0] += nbits; + if (pms->count[0] < nbits) + pms->count[1]++; + + /* Process an initial partial block. */ + if (offset) { + int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); + + memcpy(pms->buf + offset, p, copy); + if (offset + copy < 64) + return; + p += copy; + left -= copy; + md5_process(pms, pms->buf); + } + + /* Process full blocks. */ + for (; left >= 64; p += 64, left -= 64) + md5_process(pms, p); + + /* Process a final partial block. */ + if (left) + memcpy(pms->buf, p, left); +} + +void +md5_finish_(md5_state_t *pms, md5_byte_t digest[16]) +{ + static const md5_byte_t pad[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + md5_byte_t data[8]; + int i; + + /* Save the length before padding. */ + for (i = 0; i < 8; ++i) + data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); + /* Pad to 56 bytes mod 64. */ + md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); + /* Append the length. */ + md5_append(pms, data, 8); + for (i = 0; i < 16; ++i) + digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); +} diff --git a/src/engine/external/md5/md5.h b/src/engine/external/md5/md5.h new file mode 100644 index 000000000..73a077113 --- /dev/null +++ b/src/engine/external/md5/md5.h @@ -0,0 +1,91 @@ +/* + Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + L. Peter Deutsch + ghost@aladdin.com + + */ +/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */ +/* + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.h is L. Peter Deutsch + . Other authors are noted in the change history + that follows (in reverse chronological order): + + 2002-04-13 lpd Removed support for non-ANSI compilers; removed + references to Ghostscript; clarified derivation from RFC 1321; + now handles byte order either statically or dynamically. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); + added conditionalization for C++ compilation from Martin + Purschke . + 1999-05-03 lpd Original version. + */ + +#ifndef md5_INCLUDED +# define md5_INCLUDED + +/* + * This package supports both compile-time and run-time determination of CPU + * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be + * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is + * defined as non-zero, the code will be compiled to run only on big-endian + * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to + * run on either big- or little-endian CPUs, but will run slightly less + * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. + */ + +typedef unsigned char md5_byte_t; /* 8-bit byte */ +typedef unsigned int md5_word_t; /* 32-bit word */ + +/* Define the state of the MD5 Algorithm. */ +typedef struct md5_state_s { + md5_word_t count[2]; /* message length in bits, lsw first */ + md5_word_t abcd[4]; /* digest buffer */ + md5_byte_t buf[64]; /* accumulate block */ +} md5_state_t; + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Initialize the algorithm. */ +void md5_init(md5_state_t *pms); + +/* Append a string to the message. */ +void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); + +/* Finish the message and return the digest. */ +void md5_finish_(md5_state_t *pms, md5_byte_t digest[16]); + +#ifdef __cplusplus +} /* end extern "C" */ +#endif + +#endif /* md5_INCLUDED */ diff --git a/src/engine/external/zlib/VERSION.txt b/src/engine/external/zlib/VERSION.txt new file mode 100644 index 000000000..c11470058 --- /dev/null +++ b/src/engine/external/zlib/VERSION.txt @@ -0,0 +1 @@ +1.2.11 diff --git a/src/engine/external/zlib/adler32.c b/src/engine/external/zlib/adler32.c new file mode 100644 index 000000000..d0be4380a --- /dev/null +++ b/src/engine/external/zlib/adler32.c @@ -0,0 +1,186 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521U /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32_z(adler, buf, len) + uLong adler; + const Bytef *buf; + z_size_t len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + return adler32_z(adler, buf, len); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/src/engine/external/zlib/compress.c b/src/engine/external/zlib/compress.c new file mode 100644 index 000000000..e2db404ab --- /dev/null +++ b/src/engine/external/zlib/compress.c @@ -0,0 +1,86 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong left; + + left = *destLen; + *destLen = 0; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen; + sourceLen -= stream.avail_in; + } + err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH); + } while (err == Z_OK); + + *destLen = stream.total_out; + deflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/src/engine/external/zlib/crc32.c b/src/engine/external/zlib/crc32.c new file mode 100644 index 000000000..9580440c0 --- /dev/null +++ b/src/engine/external/zlib/crc32.c @@ -0,0 +1,442 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, z_size_t)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, z_size_t)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32_z(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + return crc32_z(crc, buf, len); +} + +#ifdef BYFOUR + +/* + This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit + integer pointer type. This violates the strict aliasing rule, where a + compiler can assume, for optimization purposes, that two pointers to + fundamentally different types won't ever point to the same memory. This can + manifest as a problem only if one of the pointers is written to. This code + only reads from those pointers. So long as this code remains isolated in + this compilation unit, there won't be a problem. For this reason, this code + should not be copied and pasted into a compilation unit in which other code + writes to the buffer that is passed to these routines. + */ + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *buf4++; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/src/engine/external/zlib/crc32.h b/src/engine/external/zlib/crc32.h new file mode 100644 index 000000000..9e0c77810 --- /dev/null +++ b/src/engine/external/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/src/engine/external/zlib/deflate.c b/src/engine/external/zlib/deflate.c new file mode 100644 index 000000000..1ec761448 --- /dev/null +++ b/src/engine/external/zlib/deflate.c @@ -0,0 +1,2163 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local int deflateStateCheck OF((z_streamp strm)); +local void slide_hash OF((deflate_state *s)); +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV +# pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef ZLIB_DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* =========================================================================== + * Slide the hash table when sliding the window down (could be avoided with 32 + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +local void slide_hash(s) + deflate_state *s; +{ + unsigned n, m; + Posf *p; + uInt wsize = s->w_size; + + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + } while (--n); + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif +} + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + s->status = INIT_STATE; /* to pass state test in deflateReset() */ + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = (uInt)windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = (uInt)memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +local int deflateStateCheck (strm) + z_streamp strm; +{ + deflate_state *s; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + s = strm->state; + if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE && +#ifdef GZIP + s->status != GZIP_STATE && +#endif + s->status != EXTRA_STATE && + s->status != NAME_STATE && + s->status != COMMENT_STATE && + s->status != HCRC_STATE && + s->status != BUSY_STATE && + s->status != FINISH_STATE)) + return 1; + return 0; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (deflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) + z_streamp strm; + Bytef *dictionary; + uInt *dictLength; +{ + deflate_state *s; + uInt len; + + if (deflateStateCheck(strm)) + return Z_STREAM_ERROR; + s = strm->state; + len = s->strstart + s->lookahead; + if (len > s->w_size) + len = s->w_size; + if (dictionary != Z_NULL && len) + zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len); + if (dictLength != Z_NULL) + *dictLength = len; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = +#ifdef GZIP + s->wrap == 2 ? GZIP_STATE : +#endif + s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (deflateStateCheck(strm) || strm->state->wrap != 2) + return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + s->high_water) { + /* Flush the last buffer: */ + int err = deflate(strm, Z_BLOCK); + if (err == Z_STREAM_ERROR) + return err; + if (strm->avail_out == 0) + return Z_BUF_ERROR; + } + if (s->level != level) { + if (s->level == 0 && s->matches != 0) { + if (s->matches == 1) + slide_hash(s); + else + CLEAR_HASH(s); + s->matches = 0; + } + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = (uInt)good_length; + s->max_lazy_match = (uInt)max_lazy; + s->nice_match = nice_length; + s->max_chain_length = (uInt)max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (deflateStateCheck(strm)) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; +#ifdef GZIP + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + Bytef *str; + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; +#endif + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output, except for + * some deflate_stored() output, goes through this function so some + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* =========================================================================== + * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1]. + */ +#define HCRC_UPDATE(beg) \ + do { \ + if (s->gzhead->hcrc && s->pending > (beg)) \ + strm->adler = crc32(strm->adler, s->pending_buf + (beg), \ + s->pending - (beg)); \ + } while (0) + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->avail_in != 0 && strm->next_in == Z_NULL) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + old_flush = s->last_flush; + s->last_flush = flush; + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Write the header */ + if (s->status == INIT_STATE) { + /* zlib header */ + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex; + while (s->pending + left > s->pending_buf_size) { + uInt copy = s->pending_buf_size - s->pending; + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, copy); + s->pending = s->pending_buf_size; + HCRC_UPDATE(beg); + s->gzindex += copy; + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + left -= copy; + } + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, left); + s->pending += left; + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + } + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) { + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + } + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#endif + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->level == 0 ? deflate_stored(s, flush) : + s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + + status = strm->state->status; + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (deflateStateCheck(source) || dest == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local unsigned read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = (int)s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef ZLIB_DEBUG + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* ZLIB_DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + unsigned n; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + slide_hash(s); + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* Maximum stored block length in deflate format (not including header). */ +#define MAX_STORED 65535 + +/* Minimum of a and b. */ +#define MIN(a, b) ((a) > (b) ? (b) : (a)) + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * + * In case deflateParams() is used to later switch to a non-zero compression + * level, s->matches (otherwise unused when storing) keeps track of the number + * of hash table slides to perform. If s->matches is 1, then one hash table + * slide will be done when switching. If s->matches is 2, the maximum value + * allowed here, then the hash table will be cleared, since two or more slides + * is the same as a clear. + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which + * maximizes the opportunites to have a single copy from next_in to next_out. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. + */ + unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size); + + /* Copy as many min_block or larger stored blocks directly to next_out as + * possible. If flushing, copy the remaining available input to next_out as + * stored blocks, if there is enough space. + */ + unsigned len, left, have, last = 0; + unsigned used = s->strm->avail_in; + do { + /* Set len to the maximum size block that we can copy directly with the + * available input data and output space. Set left to how much of that + * would be copied from what's left in the window. + */ + len = MAX_STORED; /* maximum deflate stored block length */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + if (s->strm->avail_out < have) /* need room for header */ + break; + /* maximum stored block length that will fit in avail_out: */ + have = s->strm->avail_out - have; + left = s->strstart - s->block_start; /* bytes left in window */ + if (len > (ulg)left + s->strm->avail_in) + len = left + s->strm->avail_in; /* limit len to the input */ + if (len > have) + len = have; /* limit len to the output */ + + /* If the stored block would be less than min_block in length, or if + * unable to copy all of the available input when flushing, then try + * copying to the window and the pending buffer instead. Also don't + * write an empty block when flushing -- deflate() does that. + */ + if (len < min_block && ((len == 0 && flush != Z_FINISH) || + flush == Z_NO_FLUSH || + len != left + s->strm->avail_in)) + break; + + /* Make a dummy stored block in pending to get the header bytes, + * including any pending bits. This also updates the debugging counts. + */ + last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; + _tr_stored_block(s, (char *)0, 0L, last); + + /* Replace the lengths in the dummy stored block with len. */ + s->pending_buf[s->pending - 4] = len; + s->pending_buf[s->pending - 3] = len >> 8; + s->pending_buf[s->pending - 2] = ~len; + s->pending_buf[s->pending - 1] = ~len >> 8; + + /* Write the stored block header bytes. */ + flush_pending(s->strm); + +#ifdef ZLIB_DEBUG + /* Update debugging counts for the data about to be copied. */ + s->compressed_len += len << 3; + s->bits_sent += len << 3; +#endif + + /* Copy uncompressed bytes from the window to next_out. */ + if (left) { + if (left > len) + left = len; + zmemcpy(s->strm->next_out, s->window + s->block_start, left); + s->strm->next_out += left; + s->strm->avail_out -= left; + s->strm->total_out += left; + s->block_start += left; + len -= left; + } + + /* Copy uncompressed bytes directly from next_in to next_out, updating + * the check value. + */ + if (len) { + read_buf(s->strm, s->strm->next_out, len); + s->strm->next_out += len; + s->strm->avail_out -= len; + s->strm->total_out += len; + } + } while (last == 0); + + /* Update the sliding window with the last s->w_size bytes of the copied + * data, or append all of the copied data to the existing window if less + * than s->w_size bytes were copied. Also update the number of bytes to + * insert in the hash tables, in the event that deflateParams() switches to + * a non-zero compression level. + */ + used -= s->strm->avail_in; /* number of input bytes directly copied */ + if (used) { + /* If any input was used, then no unused input remains in the window, + * therefore s->block_start == s->strstart. + */ + if (used >= s->w_size) { /* supplant the previous history */ + s->matches = 2; /* clear hash */ + zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); + s->strstart = s->w_size; + } + else { + if (s->window_size - s->strstart <= used) { + /* Slide the window down. */ + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + } + zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); + s->strstart += used; + } + s->block_start = s->strstart; + s->insert += MIN(used, s->w_size - s->insert); + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* If the last block was written to next_out, then done. */ + if (last) + return finish_done; + + /* If flushing and all input has been consumed, then done. */ + if (flush != Z_NO_FLUSH && flush != Z_FINISH && + s->strm->avail_in == 0 && (long)s->strstart == s->block_start) + return block_done; + + /* Fill the window with any remaining input. */ + have = s->window_size - s->strstart - 1; + if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) { + /* Slide the window down. */ + s->block_start -= s->w_size; + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + have += s->w_size; /* more space now */ + } + if (have > s->strm->avail_in) + have = s->strm->avail_in; + if (have) { + read_buf(s->strm, s->window + s->strstart, have); + s->strstart += have; + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* There was not enough avail_out to write a complete worthy or flushed + * stored block to next_out. Write a stored block to pending instead, if we + * have enough input for a worthy block, or if flushing and there is enough + * room for the remaining input as a stored block in the pending buffer. + */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + /* maximum stored block length that will fit in pending: */ + have = MIN(s->pending_buf_size - have, MAX_STORED); + min_block = MIN(have, s->w_size); + left = s->strstart - s->block_start; + if (left >= min_block || + ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && + s->strm->avail_in == 0 && left <= have)) { + len = MIN(left, have); + last = flush == Z_FINISH && s->strm->avail_in == 0 && + len == left ? 1 : 0; + _tr_stored_block(s, (charf *)s->window + s->block_start, len, last); + s->block_start += len; + flush_pending(s->strm); + } + + /* We've done all we can with the available input and output. */ + return last ? finish_started : need_more; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (uInt)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/src/engine/external/zlib/deflate.h b/src/engine/external/zlib/deflate.h new file mode 100644 index 000000000..23ecdd312 --- /dev/null +++ b/src/engine/external/zlib/deflate.h @@ -0,0 +1,349 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 /* zlib header -> BUSY_STATE */ +#ifdef GZIP +# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */ +#endif +#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */ +#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */ +#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */ +#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */ +#define BUSY_STATE 113 /* deflate -> FINISH_STATE */ +#define FINISH_STATE 666 /* stream complete */ +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + const static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + ulg pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef ZLIB_DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef ZLIB_DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (uch)(length); \ + ush dist = (ush)(distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/src/engine/external/zlib/gzguts.h b/src/engine/external/zlib/gzguts.h new file mode 100644 index 000000000..990a4d251 --- /dev/null +++ b/src/engine/external/zlib/gzguts.h @@ -0,0 +1,218 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "zlib.h" +#ifdef STDC +# include +# include +# include +#endif + +#ifndef _POSIX_SOURCE +# define _POSIX_SOURCE +#endif +#include + +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# define WIDECHAR +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99), _snprintf does not guarantee + null termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#if defined(_MSC_VER) && _MSC_VER < 1900 +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer (double-sized when writing) */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/src/engine/external/zlib/infback.c b/src/engine/external/zlib/infback.c new file mode 100644 index 000000000..59679ecbf --- /dev/null +++ b/src/engine/external/zlib/infback.c @@ -0,0 +1,640 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = (uInt)windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/src/engine/external/zlib/inffast.c b/src/engine/external/zlib/inffast.c new file mode 100644 index 000000000..0dbd1dbc0 --- /dev/null +++ b/src/engine/external/zlib/inffast.c @@ -0,0 +1,323 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - 5); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/src/engine/external/zlib/inffast.h b/src/engine/external/zlib/inffast.h new file mode 100644 index 000000000..e5c1aa4ca --- /dev/null +++ b/src/engine/external/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/src/engine/external/zlib/inffixed.h b/src/engine/external/zlib/inffixed.h new file mode 100644 index 000000000..d62832776 --- /dev/null +++ b/src/engine/external/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/src/engine/external/zlib/inflate.c b/src/engine/external/zlib/inflate.c new file mode 100644 index 000000000..ac333e8c2 --- /dev/null +++ b/src/engine/external/zlib/inflate.c @@ -0,0 +1,1561 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/src/engine/external/zlib/inflate.h b/src/engine/external/zlib/inflate.h new file mode 100644 index 000000000..a46cce6b6 --- /dev/null +++ b/src/engine/external/zlib/inflate.h @@ -0,0 +1,125 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD = 16180, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* State maintained between inflate() calls -- approximately 7K bytes, not + including the allocated sliding window, which is up to 32K bytes. */ +struct inflate_state { + z_streamp strm; /* pointer back to this zlib stream */ + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip, + bit 2 true to validate check value */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/src/engine/external/zlib/inftrees.c b/src/engine/external/zlib/inftrees.c new file mode 100644 index 000000000..2ea08fc13 --- /dev/null +++ b/src/engine/external/zlib/inftrees.c @@ -0,0 +1,304 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.11 Copyright 1995-2017 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + unsigned match; /* use base and extra for symbol >= match */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + match = 20; + break; + case LENS: + base = lbase; + extra = lext; + match = 257; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + match = 0; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if (work[sym] + 1U < match) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if (work[sym] >= match) { + here.op = (unsigned char)(extra[work[sym] - match]); + here.val = base[work[sym] - match]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/src/engine/external/zlib/inftrees.h b/src/engine/external/zlib/inftrees.h new file mode 100644 index 000000000..baa53a0b1 --- /dev/null +++ b/src/engine/external/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/src/engine/external/zlib/trees.c b/src/engine/external/zlib/trees.c new file mode 100644 index 000000000..50cf4b457 --- /dev/null +++ b/src/engine/external/zlib/trees.c @@ -0,0 +1,1203 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2017 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef ZLIB_DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local const static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local const static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local const static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef ZLIB_DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* !ZLIB_DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef ZLIB_DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !ZLIB_DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = (int)value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* ZLIB_DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef ZLIB_DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); + } + if (overflow == 0) return; + + Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + unsigned code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits-1]) << 1; + next_code[bits] = (ush)code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); + zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); + s->pending += stored_len; +#ifdef ZLIB_DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; + s->bits_sent += stored_len<<3; +#endif +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef ZLIB_DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef ZLIB_DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= (unsigned)base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} diff --git a/src/engine/external/zlib/trees.h b/src/engine/external/zlib/trees.h new file mode 100644 index 000000000..d35639d82 --- /dev/null +++ b/src/engine/external/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/src/engine/external/zlib/uncompr.c b/src/engine/external/zlib/uncompr.c new file mode 100644 index 000000000..f03a1a865 --- /dev/null +++ b/src/engine/external/zlib/uncompr.c @@ -0,0 +1,93 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. *sourceLen is + the byte length of the source buffer. Upon entry, *destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, + *destLen is the size of the decompressed data and *sourceLen is the number + of source bytes consumed. Upon return, source + *sourceLen points to the + first unused input byte. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, or + Z_DATA_ERROR if the input data was corrupted, including if the input data is + an incomplete zlib stream. +*/ +int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong *sourceLen; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong len, left; + Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */ + + len = *sourceLen; + if (*destLen) { + left = *destLen; + *destLen = 0; + } + else { + left = 1; + dest = buf; + } + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = len > (uLong)max ? max : (uInt)len; + len -= stream.avail_in; + } + err = inflate(&stream, Z_NO_FLUSH); + } while (err == Z_OK); + + *sourceLen -= len + stream.avail_in; + if (dest != buf) + *destLen = stream.total_out; + else if (stream.total_out && err == Z_BUF_ERROR) + left = 1; + + inflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : + err == Z_NEED_DICT ? Z_DATA_ERROR : + err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR : + err; +} + +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return uncompress2(dest, destLen, source, &sourceLen); +} diff --git a/src/engine/external/zlib/zconf.h b/src/engine/external/zlib/zconf.h new file mode 100644 index 000000000..5e1d68a00 --- /dev/null +++ b/src/engine/external/zlib/zconf.h @@ -0,0 +1,534 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/src/engine/external/zlib/zlib.h b/src/engine/external/zlib/zlib.h new file mode 100644 index 000000000..f09cdaf1e --- /dev/null +++ b/src/engine/external/zlib/zlib.h @@ -0,0 +1,1912 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.11" +#define ZLIB_VERNUM 0x12b0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 11 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more ouput + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if any input has been consumed in a previous + deflate() call, then the input available so far is compressed with the old + level and strategy using deflate(strm, Z_BLOCK). There are three approaches + for the compression levels 0, 1..3, and 4..9 respectively. The new level + and strategy will take effect at the next call of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will not automatically decode concatenated gzip streams. + inflate() will return Z_STREAM_END at the end of the gzip stream. The state + would need to be reset to continue decoding a subsequent gzip stream. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Three times that size in buffer space is allocated. A larger buffer + size of, for example, 64K or 128K bytes will noticeably increase the speed + of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. Previously provided + data is flushed before the parameter change. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read up to nitems items of size size from file to buf, otherwise operating + as gzread() does. This duplicates the interface of stdio's fread(), with + size_t request and return types. If the library defines size_t, then + z_size_t is identical to size_t. If not, then z_size_t is an unsigned + integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevetheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, reseting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + gzfwrite() writes nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/src/engine/external/zlib/zutil.c b/src/engine/external/zlib/zutil.c new file mode 100644 index 000000000..a76c6b0c7 --- /dev/null +++ b/src/engine/external/zlib/zutil.c @@ -0,0 +1,325 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2017 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +z_const char * const z_errmsg[10] = { + (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ + (z_const char *)"stream end", /* Z_STREAM_END 1 */ + (z_const char *)"", /* Z_OK 0 */ + (z_const char *)"file error", /* Z_ERRNO (-1) */ + (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ + (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ + (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ + (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ + (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ + (z_const char *)"" +}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef ZLIB_DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef ZLIB_DEBUG +#include +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf; + ulg bsize = (ulg)items*size; + + (void)opaque; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + + (void)opaque; + + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + (void)opaque; + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + (void)opaque; + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + (void)opaque; + free(ptr); +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/src/engine/external/zlib/zutil.h b/src/engine/external/zlib/zutil.h new file mode 100644 index 000000000..b079ea6a8 --- /dev/null +++ b/src/engine/external/zlib/zutil.h @@ -0,0 +1,271 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 1 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 2 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef __370__ +# if __TARGET_LIB__ < 0x20000000 +# define OS_CODE 4 +# elif __TARGET_LIB__ < 0x40000000 +# define OS_CODE 11 +# else +# define OS_CODE 8 +# endif +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 5 +#endif + +#ifdef OS2 +# define OS_CODE 6 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 7 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef __acorn +# define OS_CODE 13 +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) +# define OS_CODE 10 +#endif + +#ifdef _BEOS_ +# define OS_CODE 16 +#endif + +#ifdef __TOS_OS400__ +# define OS_CODE 18 +#endif + +#ifdef __APPLE__ +# define OS_CODE 19 +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 3 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef ZLIB_DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/src/engine/kernel.h b/src/engine/kernel.h new file mode 100644 index 000000000..de3696db7 --- /dev/null +++ b/src/engine/kernel.h @@ -0,0 +1,68 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_KERNEL_H +#define ENGINE_KERNEL_H + +#include + +class IKernel; +class IInterface; + +class IInterface +{ + // friend with the kernel implementation + friend class CKernel; + IKernel *m_pKernel; +protected: + IKernel *Kernel() { return m_pKernel; } +public: + IInterface() : m_pKernel(0) {} + virtual ~IInterface() {} + + //virtual unsigned InterfaceID() = 0; + //virtual const char *InterfaceName() = 0; +}; + +#define MACRO_INTERFACE(Name, ver) \ + public: \ + static const char *InterfaceName() { return Name; } \ + private: + + //virtual unsigned InterfaceID() { return INTERFACE_ID; } + //virtual const char *InterfaceName() { return name; } + + +// This kernel thingie makes the structure very flat and basiclly singletons. +// I'm not sure if this is a good idea but it works for now. +class IKernel +{ + // hide the implementation + virtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; + virtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; + virtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0; +public: + static IKernel *Create(); + virtual ~IKernel() {} + + // templated access to handle pointer conversions and interface names + template + bool RegisterInterface(TINTERFACE *pInterface) + { + return RegisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); + } + template + bool ReregisterInterface(TINTERFACE *pInterface) + { + return ReregisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); + } + + // Usage example: + // IMyInterface *pMyHandle = Kernel()->RequestInterface() + template + TINTERFACE *RequestInterface() + { + return reinterpret_cast(RequestInterfaceImpl(TINTERFACE::InterfaceName())); + } +}; + +#endif diff --git a/src/engine/map.h b/src/engine/map.h new file mode 100644 index 000000000..bdc3cc68f --- /dev/null +++ b/src/engine/map.h @@ -0,0 +1,36 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MAP_H +#define ENGINE_MAP_H + +#include +#include "kernel.h" + +class IMap : public IInterface +{ + MACRO_INTERFACE("map", 0) +public: + virtual void *GetData(int Index) = 0; + virtual void *GetDataSwapped(int Index) = 0; + virtual void UnloadData(int Index) = 0; + virtual void *GetItem(int Index, int *Type, int *pID) = 0; + virtual void GetType(int Type, int *pStart, int *pNum) = 0; + virtual void *FindItem(int Type, int ID) = 0; + virtual int NumItems() = 0; +}; + + +class IEngineMap : public IMap +{ + MACRO_INTERFACE("enginemap", 0) +public: + virtual bool Load(const char *pMapName, class IStorage *pStorage=0) = 0; + virtual bool IsLoaded() = 0; + virtual void Unload() = 0; + virtual SHA256_DIGEST Sha256() = 0; + virtual unsigned Crc() = 0; +}; + +extern IEngineMap *CreateEngineMap(); + +#endif diff --git a/src/engine/mapchecker.h b/src/engine/mapchecker.h new file mode 100644 index 000000000..c6f7cfcf8 --- /dev/null +++ b/src/engine/mapchecker.h @@ -0,0 +1,25 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MAPCHECKER_H +#define ENGINE_MAPCHECKER_H + +#include + +#include "kernel.h" + +class IMapChecker : public IInterface +{ + MACRO_INTERFACE("mapchecker", 0) +public: + virtual void AddMaplist(const struct CMapVersion *pMaplist, int Num) = 0; + virtual bool IsMapValid(const char *pMapName, const SHA256_DIGEST *pMapSha256, unsigned MapCrc, unsigned MapSize) = 0; + virtual bool ReadAndValidateMap(const char *pFilename, int StorageType) = 0; + + virtual int NumStandardMaps() = 0; + virtual const char *GetStandardMapName(int Index) = 0; + virtual bool IsStandardMap(const char *pMapName) = 0; +}; + +extern IMapChecker *CreateMapChecker(); + +#endif diff --git a/src/engine/masterserver.h b/src/engine/masterserver.h new file mode 100644 index 000000000..ab14b6ac0 --- /dev/null +++ b/src/engine/masterserver.h @@ -0,0 +1,42 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MASTERSERVER_H +#define ENGINE_MASTERSERVER_H + +#include "kernel.h" + +class IMasterServer : public IInterface +{ + MACRO_INTERFACE("masterserver", 0) +public: + + enum + { + MAX_MASTERSERVERS=4 + }; + + virtual void Init() = 0; + virtual void SetDefault() = 0; + virtual int Load() = 0; + virtual int Save() = 0; + + virtual int RefreshAddresses(int Nettype) = 0; + virtual void Update() = 0; + virtual bool IsRefreshing() const = 0; + virtual NETADDR GetAddr(int Index) const= 0; + virtual const char *GetName(int Index) const = 0; + virtual bool IsValid(int Index) const = 0; +}; + +class IEngineMasterServer : public IMasterServer +{ + MACRO_INTERFACE("enginemasterserver", 0) +public: +}; + +extern IEngineMasterServer *CreateEngineMasterServer(); + +#endif + + + diff --git a/src/engine/message.h b/src/engine/message.h new file mode 100644 index 000000000..edfef24e1 --- /dev/null +++ b/src/engine/message.h @@ -0,0 +1,18 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MESSAGE_H +#define ENGINE_MESSAGE_H + +#include + +class CMsgPacker : public CPacker +{ +public: + CMsgPacker(int Type, bool System=false) + { + Reset(); + AddInt((Type<<1)|(System?1:0)); + } +}; + +#endif diff --git a/src/engine/server.h b/src/engine/server.h new file mode 100644 index 000000000..6ac20abbf --- /dev/null +++ b/src/engine/server.h @@ -0,0 +1,110 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_H +#define ENGINE_SERVER_H +#include "kernel.h" +#include "message.h" + +class IServer : public IInterface +{ + MACRO_INTERFACE("server", 0) +protected: + int m_CurrentGameTick; + int m_TickSpeed; + +public: + /* + Structure: CClientInfo + */ + struct CClientInfo + { + const char *m_pName; + int m_Latency; + }; + + int Tick() const { return m_CurrentGameTick; } + int TickSpeed() const { return m_TickSpeed; } + + virtual const char *ClientName(int ClientID) const = 0; + virtual const char *ClientClan(int ClientID) const = 0; + virtual int ClientCountry(int ClientID) const = 0; + virtual bool ClientIngame(int ClientID) const = 0; + virtual int GetClientInfo(int ClientID, CClientInfo *pInfo) const = 0; + virtual void GetClientAddr(int ClientID, char *pAddrStr, int Size) const = 0; + virtual int GetClientVersion(int ClientID) const = 0; + + virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) = 0; + + template + int SendPackMsg(T *pMsg, int Flags, int ClientID) + { + CMsgPacker Packer(pMsg->MsgID(), false); + if(pMsg->Pack(&Packer)) + return -1; + return SendMsg(&Packer, Flags, ClientID); + } + + virtual void SetClientName(int ClientID, char const *pName) = 0; + virtual void SetClientClan(int ClientID, char const *pClan) = 0; + virtual void SetClientCountry(int ClientID, int Country) = 0; + virtual void SetClientScore(int ClientID, int Score) = 0; + + virtual int SnapNewID() = 0; + virtual void SnapFreeID(int ID) = 0; + virtual void *SnapNewItem(int Type, int ID, int Size) = 0; + + virtual void SnapSetStaticsize(int ItemType, int Size) = 0; + + enum + { + RCON_CID_SERV=-1, + RCON_CID_VOTE=-2, + }; + virtual void SetRconCID(int ClientID) = 0; + virtual bool IsAuthed(int ClientID) const = 0; + virtual bool IsBanned(int ClientID) = 0; + virtual void Kick(int ClientID, const char *pReason) = 0; + virtual void ChangeMap(const char *pMap) = 0; + + virtual void DemoRecorder_HandleAutoStart() = 0; + virtual bool DemoRecorder_IsRecording() = 0; +}; + +class IGameServer : public IInterface +{ + MACRO_INTERFACE("gameserver", 0) +protected: +public: + virtual void OnInit() = 0; + virtual void OnConsoleInit() = 0; + virtual void OnShutdown() = 0; + + virtual void OnTick() = 0; + virtual void OnPreSnap() = 0; + virtual void OnSnap(int ClientID) = 0; + virtual void OnPostSnap() = 0; + + virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) = 0; + + virtual void OnClientConnected(int ClientID, bool AsSpec) = 0; + virtual void OnClientEnter(int ClientID) = 0; + virtual void OnClientDrop(int ClientID, const char *pReason) = 0; + virtual void OnClientDirectInput(int ClientID, void *pInput) = 0; + virtual void OnClientPredictedInput(int ClientID, void *pInput) = 0; + + virtual bool IsClientBot(int ClientID) const = 0; + virtual bool IsClientReady(int ClientID) const = 0; + virtual bool IsClientPlayer(int ClientID) const = 0; + virtual bool IsClientSpectator(int ClientID) const = 0; + + virtual const char *GameType() const = 0; + virtual const char *Version() const = 0; + virtual const char *NetVersion() const = 0; + virtual const char *NetVersionHashUsed() const = 0; + virtual const char *NetVersionHashReal() const = 0; + + virtual bool TimeScore() const { return false; } +}; + +extern IGameServer *CreateGameServer(); +#endif diff --git a/src/engine/server/register.cpp b/src/engine/server/register.cpp new file mode 100644 index 000000000..6826681bc --- /dev/null +++ b/src/engine/server/register.cpp @@ -0,0 +1,288 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include +#include +#include + +#include + +#include "register.h" + +CRegister::CRegister() +{ + m_pNetServer = 0; + m_pMasterServer = 0; + m_pConfig = 0; + m_pConsole = 0; + + m_RegisterState = REGISTERSTATE_START; + m_RegisterStateStart = 0; + m_RegisterFirst = 1; + m_RegisterCount = 0; + + mem_zero(m_aMasterserverInfo, sizeof(m_aMasterserverInfo)); + m_RegisterRegisteredServer = -1; +} + +void CRegister::RegisterNewState(int State) +{ + m_RegisterState = State; + m_RegisterStateStart = time_get(); +} + +void CRegister::RegisterSendFwcheckresponse(NETADDR *pAddr, TOKEN Token) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = *pAddr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE); + Packet.m_pData = SERVERBROWSE_FWRESPONSE; + m_pNetServer->Send(&Packet, Token); +} + +void CRegister::RegisterSendHeartbeat(NETADDR Addr) +{ + static unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2]; + unsigned short Port = m_pConfig->m_SvPort; + CNetChunk Packet; + + mem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)); + + Packet.m_ClientID = -1; + Packet.m_Address = Addr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2; + Packet.m_pData = &aData; + + // supply the set port that the master can use if it has problems + if(m_pConfig->m_SvExternalPort) + Port = m_pConfig->m_SvExternalPort; + aData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8; + aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff; + m_pNetServer->Send(&Packet); +} + +void CRegister::RegisterSendCountRequest(NETADDR Addr) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = Addr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_GETCOUNT); + Packet.m_pData = SERVERBROWSE_GETCOUNT; + m_pNetServer->Send(&Packet); +} + +void CRegister::RegisterGotCount(CNetChunk *pChunk) +{ + unsigned char *pData = (unsigned char *)pChunk->m_pData; + int Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1]; + + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(net_addr_comp(&m_aMasterserverInfo[i].m_Addr, &pChunk->m_Address, true) == 0) + { + m_aMasterserverInfo[i].m_Count = Count; + break; + } + } +} + +void CRegister::Init(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, CConfig *pConfig, IConsole *pConsole) +{ + m_pNetServer = pNetServer; + m_pMasterServer = pMasterServer; + m_pConfig = pConfig; + m_pConsole = pConsole; +} + +void CRegister::RegisterUpdate(int Nettype) +{ + int64 Now = time_get(); + int64 Freq = time_freq(); + + if(!m_pConfig->m_SvRegister) + return; + + m_pMasterServer->Update(); + + if(m_RegisterState == REGISTERSTATE_START) + { + m_RegisterCount = 0; + m_RegisterFirst = 1; + RegisterNewState(REGISTERSTATE_UPDATE_ADDRS); + m_pMasterServer->RefreshAddresses(Nettype); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "refreshing ip addresses"); + } + else if(m_RegisterState == REGISTERSTATE_UPDATE_ADDRS) + { + m_RegisterRegisteredServer = -1; + + if(!m_pMasterServer->IsRefreshing()) + { + int i; + for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + { + m_aMasterserverInfo[i].m_Valid = 0; + m_aMasterserverInfo[i].m_Count = 0; + continue; + } + + NETADDR Addr = m_pMasterServer->GetAddr(i); + m_aMasterserverInfo[i].m_Addr = Addr; + m_aMasterserverInfo[i].m_Valid = 1; + m_aMasterserverInfo[i].m_Count = -1; + m_aMasterserverInfo[i].m_LastSend = 0; + } + + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "fetching server counts"); + RegisterNewState(REGISTERSTATE_QUERY_COUNT); + } + } + else if(m_RegisterState == REGISTERSTATE_QUERY_COUNT) + { + int Left = 0; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_aMasterserverInfo[i].m_Valid) + continue; + + if(m_aMasterserverInfo[i].m_Count == -1) + { + Left++; + if(m_aMasterserverInfo[i].m_LastSend+Freq < Now) + { + m_aMasterserverInfo[i].m_LastSend = Now; + RegisterSendCountRequest(m_aMasterserverInfo[i].m_Addr); + } + } + } + + // check if we are done or timed out + if(Left == 0 || Now > m_RegisterStateStart+Freq*3) + { + // choose server + int Best = -1; + int i; + for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_aMasterserverInfo[i].m_Valid || m_aMasterserverInfo[i].m_Count == -1) + continue; + + if(Best == -1 || m_aMasterserverInfo[i].m_Count < m_aMasterserverInfo[Best].m_Count) + Best = i; + } + + // server chosen + m_RegisterRegisteredServer = Best; + if(m_RegisterRegisteredServer == -1) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: No master servers. Retrying in 60 seconds"); + RegisterNewState(REGISTERSTATE_ERROR); + } + else + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "chose '%s' as master, sending heartbeats", m_pMasterServer->GetName(m_RegisterRegisteredServer)); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); + m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = 0; + RegisterNewState(REGISTERSTATE_HEARTBEAT); + } + } + } + else if(m_RegisterState == REGISTERSTATE_HEARTBEAT) + { + // check if we should send heartbeat + if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15) + { + m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now; + RegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr); + } + + if(Now > m_RegisterStateStart+Freq*60) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: Master server is not responding, switching master"); + RegisterNewState(REGISTERSTATE_START); + } + } + else if(m_RegisterState == REGISTERSTATE_REGISTERED) + { + if(m_RegisterFirst) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "server registered"); + + m_RegisterFirst = 0; + + // check if we should send new heartbeat again + if(Now > m_RegisterStateStart+Freq) + { + if(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers + RegisterNewState(REGISTERSTATE_START); + else + { + m_RegisterCount++; + RegisterNewState(REGISTERSTATE_HEARTBEAT); + } + } + } + else if(m_RegisterState == REGISTERSTATE_ERROR) + { + // check for restart + if(Now > m_RegisterStateStart+Freq*60) + RegisterNewState(REGISTERSTATE_START); + } +} + +int CRegister::RegisterProcessPacket(CNetChunk *pPacket, TOKEN Token) +{ + // check for masterserver address + bool Valid = false; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(net_addr_comp(&pPacket->m_Address, &m_aMasterserverInfo[i].m_Addr, false) == 0) + { + Valid = true; + break; + } + } + if(!Valid) + return 0; + + if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWCHECK) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0) + { + RegisterSendFwcheckresponse(&pPacket->m_Address, Token); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWOK) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0) + { + if(m_RegisterFirst && m_RegisterState != REGISTERSTATE_REGISTERED) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "no firewall/nat problems detected"); + RegisterNewState(REGISTERSTATE_REGISTERED); + m_pNetServer->AddToken(&pPacket->m_Address, Token); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWERROR) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "ERROR: the master server reports that clients can not connect to this server."); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ERROR: configure your firewall/nat to let through udp on port %d.", m_pConfig->m_SvPort); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); + RegisterNewState(REGISTERSTATE_ERROR); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 && + mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) + { + RegisterGotCount(pPacket); + return 1; + } + + return 0; +} diff --git a/src/engine/server/register.h b/src/engine/server/register.h new file mode 100644 index 000000000..eedfb18c6 --- /dev/null +++ b/src/engine/server/register.h @@ -0,0 +1,54 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_REGISTER_H +#define ENGINE_SERVER_REGISTER_H + +#include + +class CRegister +{ + enum + { + REGISTERSTATE_START=0, + REGISTERSTATE_UPDATE_ADDRS, + REGISTERSTATE_QUERY_COUNT, + REGISTERSTATE_HEARTBEAT, + REGISTERSTATE_REGISTERED, + REGISTERSTATE_ERROR + }; + + struct CMasterserverInfo + { + NETADDR m_Addr; + int m_Count; + int m_Valid; + int64 m_LastSend; + }; + + class CNetServer *m_pNetServer; + class IEngineMasterServer *m_pMasterServer; + class CConfig *m_pConfig; + class IConsole *m_pConsole; + + int m_RegisterState; + int64 m_RegisterStateStart; + int m_RegisterFirst; + int m_RegisterCount; + + CMasterserverInfo m_aMasterserverInfo[IMasterServer::MAX_MASTERSERVERS]; + int m_RegisterRegisteredServer; + + void RegisterNewState(int State); + void RegisterSendFwcheckresponse(NETADDR *pAddr, TOKEN Token); + void RegisterSendHeartbeat(NETADDR Addr); + void RegisterSendCountRequest(NETADDR Addr); + void RegisterGotCount(struct CNetChunk *pChunk); + +public: + CRegister(); + void Init(class CNetServer *pNetServer, class IEngineMasterServer *pMasterServer, class CConfig *pConfig, class IConsole *pConsole); + void RegisterUpdate(int Nettype); + int RegisterProcessPacket(struct CNetChunk *pPacket, TOKEN Token); +}; + +#endif diff --git a/src/engine/server/server.cpp b/src/engine/server/server.cpp new file mode 100644 index 000000000..50e6dfeaf --- /dev/null +++ b/src/engine/server/server.cpp @@ -0,0 +1,1959 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "register.h" +#include "server.h" + +#if defined(CONF_FAMILY_WINDOWS) + #define WIN32_LEAN_AND_MEAN + #include +#endif + +#include + +volatile sig_atomic_t InterruptSignaled = 0; + +CSnapIDPool::CSnapIDPool() +{ + Reset(); +} + +void CSnapIDPool::Reset() +{ + for(int i = 0; i < MAX_IDS; i++) + { + m_aIDs[i].m_Next = i+1; + m_aIDs[i].m_State = 0; + } + + m_aIDs[MAX_IDS-1].m_Next = -1; + m_FirstFree = 0; + m_FirstTimed = -1; + m_LastTimed = -1; + m_Usage = 0; + m_InUsage = 0; +} + + +void CSnapIDPool::RemoveFirstTimeout() +{ + int NextTimed = m_aIDs[m_FirstTimed].m_Next; + + // add it to the free list + m_aIDs[m_FirstTimed].m_Next = m_FirstFree; + m_aIDs[m_FirstTimed].m_State = 0; + m_FirstFree = m_FirstTimed; + + // remove it from the timed list + m_FirstTimed = NextTimed; + if(m_FirstTimed == -1) + m_LastTimed = -1; + + m_Usage--; +} + +int CSnapIDPool::NewID() +{ + int64 Now = time_get(); + + // process timed ids + while(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now) + RemoveFirstTimeout(); + + int ID = m_FirstFree; + dbg_assert(ID != -1, "id error"); + if(ID == -1) + return ID; + m_FirstFree = m_aIDs[m_FirstFree].m_Next; + m_aIDs[ID].m_State = 1; + m_Usage++; + m_InUsage++; + return ID; +} + +void CSnapIDPool::TimeoutIDs() +{ + // process timed ids + while(m_FirstTimed != -1) + RemoveFirstTimeout(); +} + +void CSnapIDPool::FreeID(int ID) +{ + if(ID < 0) + return; + dbg_assert(m_aIDs[ID].m_State == 1, "id is not allocated"); + + m_InUsage--; + m_aIDs[ID].m_State = 2; + m_aIDs[ID].m_Timeout = time_get()+time_freq()*5; + m_aIDs[ID].m_Next = -1; + + if(m_LastTimed != -1) + { + m_aIDs[m_LastTimed].m_Next = ID; + m_LastTimed = ID; + } + else + { + m_FirstTimed = ID; + m_LastTimed = ID; + } +} + + +void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer) +{ + CNetBan::Init(pConsole, pStorage); + + m_pServer = pServer; + + // overwrites base command, todo: improve this + Console()->Register("ban", "s[id|ip|range] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with IP/IP range/client id for x minutes for any reason"); +} + +template +int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) +{ + // validate address + if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS && + Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) + { + if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)"); + return -1; + } + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); + return -1; + } + } + } + else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); + return -1; + } + } + } + + int Result = Ban(pBanPool, pData, Seconds, pReason); + if(Result != 0) + return Result; + + // drop banned clients + typename T::CDataType Data = *pData; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i))) + { + CNetHash NetHash(&Data); + char aBuf[256]; + MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER); + Server()->m_NetServer.Drop(i, aBuf); + } + } + + return Result; +} + +int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) +{ + return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason); +} + +int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) +{ + if(pRange->IsValid()) + return BanExt(&m_BanRangePool, pRange, Seconds, pReason); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser) +{ + CServerBan *pThis = static_cast(pUser); + + const char *pStr = pResult->GetString(0); + int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; + const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; + + if(!str_is_number(pStr)) + { + int ClientID = str_toint(pStr); + if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)"); + else + pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason); + } + else + ConBan(pResult, pUser); +} + + +void CServer::CClient::Reset() +{ + // reset input + for(int i = 0; i < 200; i++) + m_aInputs[i].m_GameTick = -1; + m_CurrentInput = 0; + mem_zero(&m_LatestInput, sizeof(m_LatestInput)); + + m_Snapshots.PurgeAll(); + m_LastAckedSnapshot = -1; + m_LastInputTick = -1; + m_SnapRate = CClient::SNAPRATE_INIT; + m_Score = 0; + m_MapChunk = 0; +} + +CServer::CServer() : m_DemoRecorder(&m_SnapshotDelta) +{ + m_TickSpeed = SERVER_TICK_SPEED; + + m_pGameServer = 0; + + m_CurrentGameTick = 0; + m_RunServer = true; + + str_copy(m_aShutdownReason, "Server shutdown", sizeof(m_aShutdownReason)); + + m_pCurrentMapData = 0; + m_CurrentMapSize = 0; + + m_NumMapEntries = 0; + m_pFirstMapEntry = 0; + m_pLastMapEntry = 0; + m_pMapListHeap = 0; + + m_MapReload = false; + + m_RconClientID = IServer::RCON_CID_SERV; + m_RconAuthLevel = AUTHED_ADMIN; + + m_RconPasswordSet = 0; + m_GeneratedRconPassword = 0; + + Init(); +} + + +void CServer::SetClientName(int ClientID, const char *pName) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pName) + return; + + const char *pDefaultName = "(1)"; + pName = str_utf8_skip_whitespaces(pName); + str_utf8_copy_num(m_aClients[ClientID].m_aName, *pName ? pName : pDefaultName, sizeof(m_aClients[ClientID].m_aName), MAX_NAME_LENGTH); +} + +void CServer::SetClientClan(int ClientID, const char *pClan) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan) + return; + + str_utf8_copy_num(m_aClients[ClientID].m_aClan, pClan, sizeof(m_aClients[ClientID].m_aClan), MAX_CLAN_LENGTH); +} + +void CServer::SetClientCountry(int ClientID, int Country) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) + return; + + m_aClients[ClientID].m_Country = Country; +} + +void CServer::SetClientScore(int ClientID, int Score) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) + return; + m_aClients[ClientID].m_Score = Score; +} + +void CServer::Kick(int ClientID, const char *pReason) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id to kick"); + return; + } + else if(m_RconClientID == ClientID) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself"); + return; + } + else if(m_aClients[ClientID].m_Authed > m_RconAuthLevel) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "kick command denied"); + return; + } + + m_NetServer.Drop(ClientID, pReason); +} + +int64 CServer::TickStartTime(int Tick) +{ + return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED; +} + +int CServer::Init() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + { + m_aClients[i].m_State = CClient::STATE_EMPTY; + m_aClients[i].m_aName[0] = 0; + m_aClients[i].m_aClan[0] = 0; + m_aClients[i].m_Country = -1; + m_aClients[i].m_Snapshots.Init(); + } + + m_CurrentGameTick = 0; + + return 0; +} + +void CServer::SetRconCID(int ClientID) +{ + m_RconClientID = ClientID; +} + +bool CServer::IsAuthed(int ClientID) const +{ + return m_aClients[ClientID].m_Authed; +} + +bool CServer::IsBanned(int ClientID) +{ + return m_ServerBan.IsBanned(m_NetServer.ClientAddr(ClientID), 0, 0, 0); +} + +int CServer::GetClientInfo(int ClientID, CClientInfo *pInfo) const +{ + dbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, "client_id is not valid"); + dbg_assert(pInfo != 0, "info can not be null"); + + if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) + { + pInfo->m_pName = m_aClients[ClientID].m_aName; + pInfo->m_Latency = m_aClients[ClientID].m_Latency; + return 1; + } + return 0; +} + +void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size) const +{ + if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME) + net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false); +} + +int CServer::GetClientVersion(int ClientID) const +{ + if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME) + return m_aClients[ClientID].m_Version; + return 0; +} + +const char *CServer::ClientName(int ClientID) const +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) + return "(invalid)"; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) + return m_aClients[ClientID].m_aName; + else + return "(connecting)"; + +} + +const char *CServer::ClientClan(int ClientID) const +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) + return ""; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) + return m_aClients[ClientID].m_aClan; + else + return ""; +} + +int CServer::ClientCountry(int ClientID) const +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) + return -1; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) + return m_aClients[ClientID].m_Country; + else + return -1; +} + +bool CServer::ClientIngame(int ClientID) const +{ + return ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME; +} + +void CServer::InitRconPasswordIfUnset() +{ + if(m_RconPasswordSet) + { + return; + } + + static const char VALUES[] = "ABCDEFGHKLMNPRSTUVWXYZabcdefghjkmnopqt23456789"; + static const size_t NUM_VALUES = sizeof(VALUES) - 1; // Disregard the '\0'. + static const size_t PASSWORD_LENGTH = 6; + dbg_assert(NUM_VALUES * NUM_VALUES >= 2048, "need at least 2048 possibilities for 2-character sequences"); + // With 6 characters, we get a password entropy of log(2048) * 6/2 = 33bit. + + dbg_assert(PASSWORD_LENGTH % 2 == 0, "need an even password length"); + unsigned short aRandom[PASSWORD_LENGTH / 2]; + char aRandomPassword[PASSWORD_LENGTH+1]; + aRandomPassword[PASSWORD_LENGTH] = 0; + + secure_random_fill(aRandom, sizeof(aRandom)); + for(size_t i = 0; i < PASSWORD_LENGTH / 2; i++) + { + unsigned short RandomNumber = aRandom[i] % 2048; + aRandomPassword[2 * i + 0] = VALUES[RandomNumber / NUM_VALUES]; + aRandomPassword[2 * i + 1] = VALUES[RandomNumber % NUM_VALUES]; + } + + str_copy(Config()->m_SvRconPassword, aRandomPassword, sizeof(Config()->m_SvRconPassword)); + m_GeneratedRconPassword = 1; +} + +int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) +{ + CNetChunk Packet; + if(!pMsg) + return -1; + + // drop invalid packet + if(ClientID != -1 && (ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY || m_aClients[ClientID].m_Quitting)) + return 0; + + mem_zero(&Packet, sizeof(CNetChunk)); + Packet.m_ClientID = ClientID; + Packet.m_pData = pMsg->Data(); + Packet.m_DataSize = pMsg->Size(); + + if(Flags&MSGFLAG_VITAL) + Packet.m_Flags |= NETSENDFLAG_VITAL; + if(Flags&MSGFLAG_FLUSH) + Packet.m_Flags |= NETSENDFLAG_FLUSH; + + // write message to demo recorder + if(!(Flags&MSGFLAG_NORECORD)) + m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size()); + + if(!(Flags&MSGFLAG_NOSEND)) + { + if(ClientID == -1) + { + // broadcast + int i; + for(i = 0; i < MAX_CLIENTS; i++) + if(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting) + { + Packet.m_ClientID = i; + m_NetServer.Send(&Packet); + } + } + else + m_NetServer.Send(&Packet); + } + return 0; +} + +void CServer::DoSnapshot() +{ + GameServer()->OnPreSnap(); + + // create snapshot for demo recording + if(m_DemoRecorder.IsRecording()) + { + char aData[CSnapshot::MAX_SIZE]; + int SnapshotSize; + + // build snap and possibly add some messages + m_SnapshotBuilder.Init(); + GameServer()->OnSnap(-1); + SnapshotSize = m_SnapshotBuilder.Finish(aData); + + // write snapshot + m_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize); + } + + // create snapshots for all clients + for(int i = 0; i < MAX_CLIENTS; i++) + { + // client must be ingame to receive snapshots + if(m_aClients[i].m_State != CClient::STATE_INGAME) + continue; + + // this client is trying to recover, don't spam snapshots + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick() % SERVER_TICK_SPEED) != 0) + continue; + + // this client is trying to recover, don't spam snapshots + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0) + continue; + + { + char aData[CSnapshot::MAX_SIZE]; + CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing + char aDeltaData[CSnapshot::MAX_SIZE]; + char aCompData[CSnapshot::MAX_SIZE]; + int SnapshotSize; + int Crc; + static CSnapshot EmptySnap; + CSnapshot *pDeltashot = &EmptySnap; + int DeltashotSize; + int DeltaTick = -1; + int DeltaSize; + + m_SnapshotBuilder.Init(); + + GameServer()->OnSnap(i); + + // finish snapshot + SnapshotSize = m_SnapshotBuilder.Finish(pData); + Crc = pData->Crc(); + + // remove old snapshos + // keep 3 seconds worth of snapshots + m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3); + + // save it the snapshot + m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0); + + // find snapshot that we can perform delta against + EmptySnap.Clear(); + + { + DeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0); + if(DeltashotSize >= 0) + DeltaTick = m_aClients[i].m_LastAckedSnapshot; + else + { + // no acked package found, force client to recover rate + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL) + m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER; + } + } + + // create delta + DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData); + + if(DeltaSize > 0) + { + // compress it + int SnapshotSize; + const int MaxSize = MAX_SNAPSHOT_PACKSIZE; + int NumPackets; + + SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData, sizeof(aCompData)); + NumPackets = (SnapshotSize+MaxSize-1)/MaxSize; + + for(int n = 0, Left = SnapshotSize; Left > 0; n++) + { + int Chunk = Left < MaxSize ? Left : MaxSize; + Left -= Chunk; + + if(NumPackets == 1) + { + CMsgPacker Msg(NETMSG_SNAPSINGLE, true); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(Crc); + Msg.AddInt(Chunk); + Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + SendMsg(&Msg, MSGFLAG_FLUSH, i); + } + else + { + CMsgPacker Msg(NETMSG_SNAP, true); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(NumPackets); + Msg.AddInt(n); + Msg.AddInt(Crc); + Msg.AddInt(Chunk); + Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + SendMsg(&Msg, MSGFLAG_FLUSH, i); + } + } + } + else + { + CMsgPacker Msg(NETMSG_SNAPEMPTY, true); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + SendMsg(&Msg, MSGFLAG_FLUSH, i); + + if(DeltaSize < 0) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "delta pack failed! (%d)", DeltaSize); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + } + } + + GameServer()->OnPostSnap(); +} + + +int CServer::NewClientCallback(int ClientID, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + + // Remove non human player on same slot + if(pThis->GameServer()->IsClientBot(ClientID)) + { + pThis->GameServer()->OnClientDrop(ClientID, "removing dummy"); + } + + pThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH; + pThis->m_aClients[ClientID].m_aName[0] = 0; + pThis->m_aClients[ClientID].m_aClan[0] = 0; + pThis->m_aClients[ClientID].m_Country = -1; + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_AuthTries = 0; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + pThis->m_aClients[ClientID].m_pMapListEntryToSend = 0; + pThis->m_aClients[ClientID].m_NoRconNote = false; + pThis->m_aClients[ClientID].m_Quitting = false; + pThis->m_aClients[ClientID].m_Latency = 0; + pThis->m_aClients[ClientID].Reset(); + + return 0; +} + +int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + // notify the mod about the drop + if(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY) + { + pThis->m_aClients[ClientID].m_Quitting = true; + pThis->GameServer()->OnClientDrop(ClientID, pReason); + } + + pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; + pThis->m_aClients[ClientID].m_aName[0] = 0; + pThis->m_aClients[ClientID].m_aClan[0] = 0; + pThis->m_aClients[ClientID].m_Country = -1; + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_AuthTries = 0; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + pThis->m_aClients[ClientID].m_pMapListEntryToSend = 0; + pThis->m_aClients[ClientID].m_NoRconNote = false; + pThis->m_aClients[ClientID].m_Quitting = false; + pThis->m_aClients[ClientID].m_Snapshots.PurgeAll(); + return 0; +} + +void CServer::SendMap(int ClientID) +{ + CMsgPacker Msg(NETMSG_MAP_CHANGE, true); + Msg.AddString(GetMapName(), 0); + Msg.AddInt(m_CurrentMapCrc); + Msg.AddInt(m_CurrentMapSize); + Msg.AddInt(m_MapChunksPerRequest); + Msg.AddInt(MAP_CHUNK_SIZE); + Msg.AddRaw(&m_CurrentMapSha256, sizeof(m_CurrentMapSha256)); + SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); +} + +void CServer::SendConnectionReady(int ClientID) +{ + CMsgPacker Msg(NETMSG_CON_READY, true); + SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); +} + +void CServer::SendRconLine(int ClientID, const char *pLine) +{ + CMsgPacker Msg(NETMSG_RCON_LINE, true); + Msg.AddString(pLine, 512); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CServer::SendRconLineAuthed(const char *pLine, void *pUser, bool Highlighted) +{ + static bool s_ReentryGuard = false; + if(s_ReentryGuard) + return; + s_ReentryGuard = true; + + CServer *pThis = (CServer *)pUser; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed >= pThis->m_RconAuthLevel) + pThis->SendRconLine(i, pLine); + } + + s_ReentryGuard = false; +} + +void CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID) +{ + CMsgPacker Msg(NETMSG_RCON_CMD_ADD, true); + Msg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH); + Msg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); + Msg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID) +{ + CMsgPacker Msg(NETMSG_RCON_CMD_REM, true); + Msg.AddString(pCommandInfo->m_pName, 256); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CServer::UpdateClientRconCommands() +{ + for(int ClientID = Tick() % MAX_RCONCMD_RATIO; ClientID < MAX_CLIENTS; ClientID += MAX_RCONCMD_RATIO) + { + if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed) + { + int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD; + for(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i) + { + SendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID); + m_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER); + } + } + } +} + +void CServer::SendMapListEntryAdd(const CMapListEntry *pMapListEntry, int ClientID) +{ + CMsgPacker Msg(NETMSG_MAPLIST_ENTRY_ADD, true); + Msg.AddString(pMapListEntry->m_aName, 256); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CServer::SendMapListEntryRem(const CMapListEntry *pMapListEntry, int ClientID) +{ + CMsgPacker Msg(NETMSG_MAPLIST_ENTRY_REM, true); + Msg.AddString(pMapListEntry->m_aName, 256); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + + +void CServer::UpdateClientMapListEntries() +{ + for(int ClientID = Tick() % MAX_RCONCMD_RATIO; ClientID < MAX_CLIENTS; ClientID += MAX_RCONCMD_RATIO) + { + if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed) + { + for(int i = 0; i < MAX_MAPLISTENTRY_SEND && m_aClients[ClientID].m_pMapListEntryToSend; ++i) + { + SendMapListEntryAdd(m_aClients[ClientID].m_pMapListEntryToSend, ClientID); + m_aClients[ClientID].m_pMapListEntryToSend = m_aClients[ClientID].m_pMapListEntryToSend->m_pNext; + } + } + } +} + +void CServer::ProcessClientPacket(CNetChunk *pPacket) +{ + int ClientID = pPacket->m_ClientID; + CUnpacker Unpacker; + Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize); + + // unpack msgid and system flag + int Msg = Unpacker.GetInt(); + int Sys = Msg&1; + Msg >>= 1; + + if(Unpacker.Error()) + return; + + if(Sys) + { + // system message + if(Msg == NETMSG_INFO) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_AUTH) + { + const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(str_comp(pVersion, GameServer()->NetVersion()) != 0) + { + // wrong version + char aReason[256]; + str_format(aReason, sizeof(aReason), "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion); + m_NetServer.Drop(ClientID, aReason); + return; + } + + const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(Config()->m_Password[0] != 0 && str_comp(Config()->m_Password, pPassword) != 0) + { + // wrong password + m_NetServer.Drop(ClientID, "Wrong password"); + return; + } + + m_aClients[ClientID].m_Version = Unpacker.GetInt(); + + m_aClients[ClientID].m_State = CClient::STATE_CONNECTING; + SendMap(ClientID); + } + } + else if(Msg == NETMSG_REQUEST_MAP_DATA) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && (m_aClients[ClientID].m_State == CClient::STATE_CONNECTING || m_aClients[ClientID].m_State == CClient::STATE_CONNECTING_AS_SPEC)) + { + int ChunkSize = MAP_CHUNK_SIZE; + + // send map chunks + for(int i = 0; i < m_MapChunksPerRequest && m_aClients[ClientID].m_MapChunk >= 0; ++i) + { + int Chunk = m_aClients[ClientID].m_MapChunk; + int Offset = Chunk * ChunkSize; + + // check for last part + if(Offset+ChunkSize >= m_CurrentMapSize) + { + ChunkSize = m_CurrentMapSize-Offset; + m_aClients[ClientID].m_MapChunk = -1; + } + else + m_aClients[ClientID].m_MapChunk++; + + CMsgPacker Msg(NETMSG_MAP_DATA, true); + Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize); + SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + + if(Config()->m_Debug) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + } + } + else if(Msg == NETMSG_READY) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && (m_aClients[ClientID].m_State == CClient::STATE_CONNECTING || m_aClients[ClientID].m_State == CClient::STATE_CONNECTING_AS_SPEC)) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%d addr=%s", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + + bool ConnectAsSpec = m_aClients[ClientID].m_State == CClient::STATE_CONNECTING_AS_SPEC; + m_aClients[ClientID].m_State = CClient::STATE_READY; + GameServer()->OnClientConnected(ClientID, ConnectAsSpec); + SendConnectionReady(ClientID); + } + } + else if(Msg == NETMSG_ENTERGAME) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID)) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%d addr=%s", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + m_aClients[ClientID].m_State = CClient::STATE_INGAME; + SendServerInfo(ClientID); + GameServer()->OnClientEnter(ClientID); + } + } + else if(Msg == NETMSG_INPUT) + { + CClient::CInput *pInput; + int64 TagTime; + int64 Now = time_get(); + + m_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt(); + int IntendedTick = Unpacker.GetInt(); + int Size = Unpacker.GetInt(); + + // check for errors + if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE) + return; + + if(m_aClients[ClientID].m_LastAckedSnapshot > 0) + m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL; + + // add message to report the input timing + // skip packets that are old + if(IntendedTick > m_aClients[ClientID].m_LastInputTick) + { + int TimeLeft = ((TickStartTime(IntendedTick)-Now)*1000) / time_freq(); + + CMsgPacker Msg(NETMSG_INPUTTIMING, true); + Msg.AddInt(IntendedTick); + Msg.AddInt(TimeLeft); + SendMsg(&Msg, 0, ClientID); + } + + m_aClients[ClientID].m_LastInputTick = IntendedTick; + + pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput]; + + if(IntendedTick <= Tick()) + IntendedTick = Tick()+1; + + pInput->m_GameTick = IntendedTick; + + for(int i = 0; i < Size/4; i++) + pInput->m_aData[i] = Unpacker.GetInt(); + + int PingCorrection = clamp(Unpacker.GetInt(), 0, 50); + if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0) + { + m_aClients[ClientID].m_Latency = (int)(((Now-TagTime)*1000)/time_freq()); + m_aClients[ClientID].m_Latency = maximum(0, m_aClients[ClientID].m_Latency - PingCorrection); + } + + mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int)); + + m_aClients[ClientID].m_CurrentInput++; + m_aClients[ClientID].m_CurrentInput %= 200; + + // call the mod with the fresh input data + if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) + GameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData); + } + else if(Msg == NETMSG_RCON_CMD) + { + const char *pCmd = Unpacker.GetString(); + + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + m_RconClientID = ClientID; + m_RconAuthLevel = m_aClients[ClientID].m_Authed; + Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD); + Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER); + Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN); + m_RconClientID = IServer::RCON_CID_SERV; + m_RconAuthLevel = AUTHED_ADMIN; + } + } + else if(Msg == NETMSG_RCON_AUTH) + { + const char *pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC); + + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0) + { + if(Config()->m_SvRconPassword[0] == 0 && Config()->m_SvRconModPassword[0] == 0) + { + if(!m_aClients[ClientID].m_NoRconNote) + { + SendRconLine(ClientID, "No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console."); + m_aClients[ClientID].m_NoRconNote = true; + } + } + else if(Config()->m_SvRconPassword[0] && str_comp(pPw, Config()->m_SvRconPassword) == 0) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_ON, true); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); + + m_aClients[ClientID].m_Authed = AUTHED_ADMIN; + m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_ADMIN, CFGFLAG_SERVER); + if(m_aClients[ClientID].m_Version >= MIN_MAPLIST_CLIENTVERSION) + m_aClients[ClientID].m_pMapListEntryToSend = m_pFirstMapEntry; + SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted."); + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d addr=%s authed (admin)", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } + else if(Config()->m_SvRconModPassword[0] && str_comp(pPw, Config()->m_SvRconModPassword) == 0) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_ON, true); + SendMsg(&Msg, MSGFLAG_VITAL, ClientID); + + m_aClients[ClientID].m_Authed = AUTHED_MOD; + m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_MOD, CFGFLAG_SERVER); + SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted."); + const IConsole::CCommandInfo *pInfo = Console()->GetCommandInfo("sv_map", CFGFLAG_SERVER, false); + if(pInfo && pInfo->GetAccessLevel() == IConsole::ACCESS_LEVEL_MOD && m_aClients[ClientID].m_Version >= MIN_MAPLIST_CLIENTVERSION) + m_aClients[ClientID].m_pMapListEntryToSend = m_pFirstMapEntry; + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d addr=%s authed (moderator)", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } + else if(Config()->m_SvRconMaxTries && m_ServerBan.IsBannable(m_NetServer.ClientAddr(ClientID))) + { + m_aClients[ClientID].m_AuthTries++; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, Config()->m_SvRconMaxTries); + SendRconLine(ClientID, aBuf); + if(m_aClients[ClientID].m_AuthTries >= Config()->m_SvRconMaxTries) + { + if(!Config()->m_SvRconBantime) + m_NetServer.Drop(ClientID, "Too many remote console authentication tries"); + else + m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), Config()->m_SvRconBantime*60, "Too many remote console authentication tries"); + } + } + else + { + SendRconLine(ClientID, "Wrong password."); + } + } + } + else if(Msg == NETMSG_PING) + { + CMsgPacker Msg(NETMSG_PING_REPLY, true); + SendMsg(&Msg, 0, ClientID); + } + else + { + if(Config()->m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "strange message ClientID=%d msg=%d data_size=%d", ClientID, Msg, pPacket->m_DataSize); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + str_hex(aBuf, sizeof(aBuf), pPacket->m_pData, minimum(pPacket->m_DataSize, 32)); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + } + else + { + // game message + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State >= CClient::STATE_READY) + GameServer()->OnMessage(Msg, &Unpacker, ClientID); + } +} + +void CServer::GenerateServerInfo(CPacker *pPacker, int Token) +{ + // count the players + int PlayerCount = 0, ClientCount = 0; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + { + if(GameServer()->IsClientPlayer(i)) + PlayerCount++; + + ClientCount++; + } + } + + if(Token != -1) + { + pPacker->Reset(); + pPacker->AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)); + pPacker->AddInt(Token); + } + + pPacker->AddString(GameServer()->Version(), 32); + pPacker->AddString(Config()->m_SvName, 64); + pPacker->AddString(Config()->m_SvHostname, 128); + pPacker->AddString(GetMapName(), 32); + + // gametype + pPacker->AddString(GameServer()->GameType(), 16); + + // flags + int Flags = 0; + if(Config()->m_Password[0]) // password set + Flags |= SERVERINFO_FLAG_PASSWORD; + if(GameServer()->TimeScore()) + Flags |= SERVERINFO_FLAG_TIMESCORE; + pPacker->AddInt(Flags); + + pPacker->AddInt(Config()->m_SvSkillLevel); // server skill level + pPacker->AddInt(PlayerCount); // num players + pPacker->AddInt(Config()->m_SvPlayerSlots); // max players + pPacker->AddInt(ClientCount); // num clients + pPacker->AddInt(maximum(ClientCount, Config()->m_SvMaxClients)); // max clients + + if(Token != -1) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + { + pPacker->AddString(ClientName(i), 0); // client name + pPacker->AddString(ClientClan(i), 0); // client clan + pPacker->AddInt(m_aClients[i].m_Country); // client country + pPacker->AddInt(m_aClients[i].m_Score); // client score + pPacker->AddInt(GameServer()->IsClientPlayer(i)?0:1); // flag spectator=1, bot=2 (player=0) + } + } + } +} + +void CServer::SendServerInfo(int ClientID) +{ + CMsgPacker Msg(NETMSG_SERVERINFO, true); + GenerateServerInfo(&Msg, -1); + if(ClientID == -1) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, i); + } + } + else if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State != CClient::STATE_EMPTY) + SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); +} + + +void CServer::PumpNetwork() +{ + CNetChunk Packet; + TOKEN ResponseToken; + + m_NetServer.Update(); + + // process packets + while(m_NetServer.Recv(&Packet, &ResponseToken)) + { + if(Packet.m_Flags&NETSENDFLAG_CONNLESS) + { + if(m_Register.RegisterProcessPacket(&Packet, ResponseToken)) + continue; + if(Packet.m_DataSize >= int(sizeof(SERVERBROWSE_GETINFO)) && + mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0) + { + CUnpacker Unpacker; + Unpacker.Reset((unsigned char*)Packet.m_pData+sizeof(SERVERBROWSE_GETINFO), Packet.m_DataSize-sizeof(SERVERBROWSE_GETINFO)); + int SrvBrwsToken = Unpacker.GetInt(); + if(Unpacker.Error()) + continue; + + CPacker Packer; + CNetChunk Response; + + GenerateServerInfo(&Packer, SrvBrwsToken); + + Response.m_ClientID = -1; + Response.m_Address = Packet.m_Address; + Response.m_Flags = NETSENDFLAG_CONNLESS; + Response.m_pData = Packer.Data(); + Response.m_DataSize = Packer.Size(); + m_NetServer.Send(&Response, ResponseToken); + } + } + else + ProcessClientPacket(&Packet); + } + + m_ServerBan.Update(); + m_Econ.Update(); +} + +const char *CServer::GetMapName() +{ + // get the name of the map without his path + char *pMapShortName = &Config()->m_SvMap[0]; + for(int i = 0; i < str_length(Config()->m_SvMap)-1; i++) + { + if(Config()->m_SvMap[i] == '/' || Config()->m_SvMap[i] == '\\') + pMapShortName = &Config()->m_SvMap[i+1]; + } + return pMapShortName; +} + +void CServer::ChangeMap(const char *pMap) +{ + str_copy(Config()->m_SvMap, pMap, sizeof(Config()->m_SvMap)); + m_MapReload = str_comp(Config()->m_SvMap, m_aCurrentMap) != 0; +} + +int CServer::LoadMap(const char *pMapName) +{ + char aBuf[IO_MAX_PATH_LENGTH]; + str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); + + // check for valid standard map + if(!m_pMapChecker->ReadAndValidateMap(aBuf, IStorage::TYPE_ALL)) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map"); + return 0; + } + + if(!m_pMap->Load(aBuf)) + return 0; + + // stop recording when we change map + if(m_DemoRecorder.IsRecording()) + m_DemoRecorder.Stop(); + + // reinit snapshot ids + m_IDPool.TimeoutIDs(); + + // get the sha256 and crc of the map + m_CurrentMapSha256 = m_pMap->Sha256(); + m_CurrentMapCrc = m_pMap->Crc(); + char aSha256[SHA256_MAXSTRSIZE]; + sha256_str(m_CurrentMapSha256, aSha256, sizeof(aSha256)); + char aBufMsg[256]; + str_format(aBufMsg, sizeof(aBufMsg), "%s sha256 is %s", aBuf, aSha256); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg); + str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg); + + str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap)); + + // load complete map into memory for download + { + IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); + m_CurrentMapSize = (int)io_length(File); + if(m_pCurrentMapData) + mem_free(m_pCurrentMapData); + m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize); + io_read(File, m_pCurrentMapData, m_CurrentMapSize); + io_close(File); + } + return 1; +} + +void CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, CConfig *pConfig, IConsole *pConsole) +{ + m_Register.Init(pNetServer, pMasterServer, pConfig, pConsole); +} + +void CServer::InitInterfaces(IKernel *pKernel) +{ + m_pConfig = pKernel->RequestInterface()->Values(); + m_pConsole = pKernel->RequestInterface(); + m_pGameServer = pKernel->RequestInterface(); + m_pMap = pKernel->RequestInterface(); + m_pMapChecker = pKernel->RequestInterface(); + m_pStorage = pKernel->RequestInterface(); +} + +int CServer::Run() +{ + // + m_PrintCBIndex = Console()->RegisterPrintCallback(Config()->m_ConsoleOutputLevel, SendRconLineAuthed, this); + + InitMapList(); + + // load map + if(!LoadMap(Config()->m_SvMap)) + { + dbg_msg("server", "failed to load map. mapname='%s'", Config()->m_SvMap); + Free(); + return -1; + } + m_MapChunksPerRequest = Config()->m_SvMapDownloadSpeed; + + // start server + NETADDR BindAddr; + if(Config()->m_Bindaddr[0] && net_host_lookup(Config()->m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // sweet! + BindAddr.type = NETTYPE_ALL; + BindAddr.port = Config()->m_SvPort; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = Config()->m_SvPort; + } + + if(!m_NetServer.Open(BindAddr, Config(), Console(), Kernel()->RequestInterface(), &m_ServerBan, + Config()->m_SvMaxClients, Config()->m_SvMaxClientsPerIP, NewClientCallback, DelClientCallback, this)) + { + dbg_msg("server", "couldn't open socket. port %d might already be in use", Config()->m_SvPort); + Free(); + return -1; + } + + m_Econ.Init(Config(), Console(), &m_ServerBan); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "server name is '%s'", Config()->m_SvName); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + GameServer()->OnInit(); + str_format(aBuf, sizeof(aBuf), "netversion %s", GameServer()->NetVersion()); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + if(str_comp(GameServer()->NetVersionHashUsed(), GameServer()->NetVersionHashReal())) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "WARNING: netversion hash differs"); + } + str_format(aBuf, sizeof(aBuf), "game version %s", GameServer()->Version()); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + // process pending commands + m_pConsole->StoreCommands(false); + + if(m_GeneratedRconPassword) + { + dbg_msg("server", "+-------------------------+"); + dbg_msg("server", "| rcon password: '%s' |", Config()->m_SvRconPassword); + dbg_msg("server", "+-------------------------+"); + } + + // start game + { + m_GameStartTime = time_get(); + + while(m_RunServer) + { + // load new map + if(m_MapReload || m_CurrentGameTick >= 0x6FFFFFFF) // force reload to make sure the ticks stay within a valid range + { + m_MapReload = false; + + // load map + if(LoadMap(Config()->m_SvMap)) + { + // new map loaded + bool aSpecs[MAX_CLIENTS]; + for(int c = 0; c < MAX_CLIENTS; c++) + aSpecs[c] = GameServer()->IsClientSpectator(c); + + GameServer()->OnShutdown(); + + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(m_aClients[c].m_State <= CClient::STATE_AUTH) + continue; + + SendMap(c); + m_aClients[c].Reset(); + m_aClients[c].m_State = aSpecs[c] ? CClient::STATE_CONNECTING_AS_SPEC : CClient::STATE_CONNECTING; + } + + m_GameStartTime = time_get(); + m_CurrentGameTick = 0; + Kernel()->ReregisterInterface(GameServer()); + GameServer()->OnInit(); + } + else + { + str_format(aBuf, sizeof(aBuf), "failed to load map. mapname='%s'", Config()->m_SvMap); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + str_copy(Config()->m_SvMap, m_aCurrentMap, sizeof(Config()->m_SvMap)); + } + } + + int64 Now = time_get(); + bool NewTicks = false; + bool ShouldSnap = false; + while(Now > TickStartTime(m_CurrentGameTick+1)) + { + m_CurrentGameTick++; + NewTicks = true; + if((m_CurrentGameTick%2) == 0) + ShouldSnap = true; + + // apply new input + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(m_aClients[c].m_State == CClient::STATE_EMPTY) + continue; + for(int i = 0; i < 200; i++) + { + if(m_aClients[c].m_aInputs[i].m_GameTick == Tick()) + { + if(m_aClients[c].m_State == CClient::STATE_INGAME) + GameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData); + break; + } + } + } + + GameServer()->OnTick(); + } + + // snap game + if(NewTicks) + { + if(Config()->m_SvHighBandwidth || ShouldSnap) + DoSnapshot(); + + UpdateClientRconCommands(); + UpdateClientMapListEntries(); + } + + // master server stuff + m_Register.RegisterUpdate(m_NetServer.NetType()); + + PumpNetwork(); + + // wait for incoming data + m_NetServer.Wait(clamp(int((TickStartTime(m_CurrentGameTick+1)-time_get())*1000/time_freq()), 1, 1000/SERVER_TICK_SPEED/2)); + + if(InterruptSignaled) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "interrupted"); + break; + } + } + } + // disconnect all clients on shutdown + m_NetServer.Close(m_aShutdownReason); + m_Econ.Shutdown(); + + GameServer()->OnShutdown(); + Free(); + + return 0; +} + +void CServer::Free() +{ + if(m_pMap) + { + m_pMap->Unload(); + } + + if(m_pCurrentMapData) + { + mem_free(m_pCurrentMapData); + m_pCurrentMapData = 0; + } + + if(m_pMapListHeap) + { + delete m_pMapListHeap; + m_pMapListHeap = 0; + } +} + +struct CSubdirCallbackUserdata +{ + CServer *m_pServer; + char m_aName[IConsole::TEMPMAP_NAME_LENGTH]; + bool m_StandardOnly; +}; + +int CServer::MapListEntryCallback(const char *pFilename, int IsDir, int DirType, void *pUser) +{ + CSubdirCallbackUserdata *pUserdata = (CSubdirCallbackUserdata *)pUser; + CServer *pThis = pUserdata->m_pServer; + + if(pFilename[0] == '.') // hidden files + return 0; + + char aFilename[IO_MAX_PATH_LENGTH]; + if(pUserdata->m_aName[0]) + str_format(aFilename, sizeof(aFilename), "%s/%s", pUserdata->m_aName, pFilename); + else + str_format(aFilename, sizeof(aFilename), "%s", pFilename); + + if(IsDir) + { + CSubdirCallbackUserdata Userdata; + Userdata.m_StandardOnly = pUserdata->m_StandardOnly; + Userdata.m_pServer = pThis; + str_copy(Userdata.m_aName, aFilename, sizeof(Userdata.m_aName)); + char aFindPath[IO_MAX_PATH_LENGTH]; + str_format(aFindPath, sizeof(aFindPath), "maps/%s/", aFilename); + pThis->m_pStorage->ListDirectory(IStorage::TYPE_ALL, aFindPath, MapListEntryCallback, &Userdata); + return 0; + } + + const char *pSuffix = str_endswith(aFilename, ".map"); + if(!pSuffix) // not ending with .map + return 0; + aFilename[pSuffix - aFilename] = 0; // remove suffix + + if(pUserdata->m_StandardOnly && !pThis->m_pMapChecker->IsStandardMap(aFilename)) + return 0; + + CMapListEntry *pEntry = (CMapListEntry *)pThis->m_pMapListHeap->Allocate(sizeof(CMapListEntry)); + pThis->m_NumMapEntries++; + pEntry->m_pNext = 0; + pEntry->m_pPrev = pThis->m_pLastMapEntry; + if(pEntry->m_pPrev) + pEntry->m_pPrev->m_pNext = pEntry; + pThis->m_pLastMapEntry = pEntry; + if(!pThis->m_pFirstMapEntry) + pThis->m_pFirstMapEntry = pEntry; + + str_copy(pEntry->m_aName, aFilename, sizeof(pEntry->m_aName)); + + return 0; +} + +void CServer::InitMapList() +{ + m_pMapListHeap = new CHeap(); + + CSubdirCallbackUserdata Userdata; + if(str_comp(Config()->m_SvMaplist, "standard") == 0) + Userdata.m_StandardOnly = true; + else if(str_comp(Config()->m_SvMaplist, "all") == 0) + Userdata.m_StandardOnly = false; + else /* "none" or any other value */ + return; + + Userdata.m_pServer = this; + str_copy(Userdata.m_aName, "", sizeof(Userdata.m_aName)); + m_pStorage->ListDirectory(IStorage::TYPE_ALL, "maps/", MapListEntryCallback, &Userdata); + dbg_msg("server", "%d maps added to maplist", m_NumMapEntries); +} + +void CServer::ConKick(IConsole::IResult *pResult, void *pUser) +{ + if(pResult->NumArguments() > 1) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Kicked (%s)", pResult->GetString(1)); + ((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf); + } + else + ((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console"); +} + +void CServer::ConStatus(IConsole::IResult *pResult, void *pUser) +{ + char aBuf[1024]; + char aAddrStr[NETADDR_MAXSTRSIZE]; + CServer* pThis = static_cast(pUser); + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY) + { + net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true); + if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME) + { + const char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? "(Admin)" : + pThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? "(Mod)" : ""; + str_format(aBuf, sizeof(aBuf), "id=%d addr=%s client=%x name='%s' score=%d %s", i, aAddrStr, + pThis->m_aClients[i].m_Version, pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, pAuthStr); + } + else + str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } + } +} + +void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser) +{ + CServer *pThis = static_cast(pUser); + pThis->m_RunServer = false; + const char *pReason = pResult->GetString(0); + if(pReason[0]) + { + str_copy(pThis->m_aShutdownReason, pReason, sizeof(pThis->m_aShutdownReason)); + } +} + +void CServer::DemoRecorder_HandleAutoStart() +{ + if(Config()->m_SvAutoDemoRecord) + { + if(m_DemoRecorder.IsRecording()) + m_DemoRecorder.Stop(); + char aFilename[128]; + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", "auto/autorecord", aDate); + m_DemoRecorder.Start(aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapSha256, m_CurrentMapCrc, "server"); + if(Config()->m_SvAutoDemoMax) + { + // clean up auto recorded demos + CFileCollection AutoDemos; + AutoDemos.Init(Storage(), "demos/server", "autorecord", ".demo", Config()->m_SvAutoDemoMax); + } + } +} + +bool CServer::DemoRecorder_IsRecording() +{ + return m_DemoRecorder.IsRecording(); +} + +void CServer::ConRecord(IConsole::IResult *pResult, void *pUser) +{ + CServer* pServer = (CServer *)pUser; + char aFilename[128]; + if(pResult->NumArguments()) + str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pResult->GetString(0)); + else + { + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "demos/demo_%s.demo", aDate); + } + pServer->m_DemoRecorder.Start(aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapSha256, pServer->m_CurrentMapCrc, "server"); +} + +void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser) +{ + ((CServer *)pUser)->m_DemoRecorder.Stop(); +} + +void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser) +{ + ((CServer *)pUser)->m_MapReload = true; +} + +void CServer::ConLogout(IConsole::IResult *pResult, void *pUser) +{ + CServer *pServer = (CServer *)pUser; + + if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS && + pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_OFF, true); + pServer->SendMsg(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID); + + pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO; + pServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0; + pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0; + pServer->m_aClients[pServer->m_RconClientID].m_pMapListEntryToSend = 0; + pServer->SendRconLine(pServer->m_RconClientID, "Logout successful."); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID); + pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } +} + +void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + CServer *pSelf = (CServer *)pUserData; + if(pResult->NumArguments()) + { + str_clean_whitespaces(pSelf->Config()->m_SvName); + pSelf->SendServerInfo(-1); + } +} + +void CServer::ConchainPlayerSlotsUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + CServer *pSelf = (CServer *)pUserData; + if(pResult->NumArguments()) + { + if(pSelf->Config()->m_SvMaxClients < pSelf->Config()->m_SvPlayerSlots) + pSelf->Config()->m_SvPlayerSlots = pSelf->Config()->m_SvMaxClients; + } +} + +void CServer::ConchainMaxclientsUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + CServer *pSelf = (CServer *)pUserData; + if(pResult->NumArguments()) + { + if(pSelf->Config()->m_SvMaxClients < pSelf->Config()->m_SvPlayerSlots) + pSelf->Config()->m_SvPlayerSlots = pSelf->Config()->m_SvMaxClients; + pSelf->m_NetServer.SetMaxClients(pResult->GetInteger(0)); + } +} + +void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0)); +} + +void CServer::ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + if(pResult->NumArguments() == 2) + { + CServer *pThis = static_cast(pUserData); + const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false); + int OldAccessLevel = 0; + if(pInfo) + OldAccessLevel = pInfo->GetAccessLevel(); + pfnCallback(pResult, pCallbackUserData); + if(pInfo && OldAccessLevel != pInfo->GetAccessLevel()) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || pThis->m_aClients[i].m_Authed != CServer::AUTHED_MOD || + (pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0)) + continue; + + if(OldAccessLevel == IConsole::ACCESS_LEVEL_ADMIN) + pThis->SendRconCmdAdd(pInfo, i); + else + pThis->SendRconCmdRem(pInfo, i); + } + } + } + else + pfnCallback(pResult, pCallbackUserData); +} + +void CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CServer *pThis = static_cast(pUserData); + pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); + } +} + +void CServer::ConchainRconPasswordSet(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() >= 1) + { + static_cast(pUserData)->m_RconPasswordSet = 1; + } +} + +void CServer::ConchainMapUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() >= 1) + { + CServer *pThis = static_cast(pUserData); + pThis->m_MapReload = str_comp(pThis->Config()->m_SvMap, pThis->m_aCurrentMap) != 0; + } +} + +void CServer::RegisterCommands() +{ + // register console commands + Console()->Register("kick", "i[id] ?r[reason]", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason"); + Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players"); + Console()->Register("shutdown", "?r[reason]", CFGFLAG_SERVER, ConShutdown, this, "Shut down"); + Console()->Register("logout", "", CFGFLAG_SERVER|CFGFLAG_BASICACCESS, ConLogout, this, "Logout of rcon"); + + Console()->Register("record", "?s[file]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file"); + Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording"); + + Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map"); + + Console()->Chain("sv_name", ConchainSpecialInfoupdate, this); + Console()->Chain("password", ConchainSpecialInfoupdate, this); + + Console()->Chain("sv_player_slots", ConchainPlayerSlotsUpdate, this); + Console()->Chain("sv_max_clients", ConchainMaxclientsUpdate, this); + Console()->Chain("sv_max_clients", ConchainSpecialInfoupdate, this); + Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this); + Console()->Chain("mod_command", ConchainModCommandUpdate, this); + Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this); + Console()->Chain("sv_rcon_password", ConchainRconPasswordSet, this); + Console()->Chain("sv_map", ConchainMapUpdate, this); + + // register console commands in sub parts + m_ServerBan.InitServerBan(Console(), Storage(), this); + m_DemoRecorder.Init(Console(), Storage()); + m_pGameServer->OnConsoleInit(); +} + + +int CServer::SnapNewID() +{ + return m_IDPool.NewID(); +} + +void CServer::SnapFreeID(int ID) +{ + m_IDPool.FreeID(ID); +} + + +void *CServer::SnapNewItem(int Type, int ID, int Size) +{ + dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type"); + dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id"); + return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size); +} + +void CServer::SnapSetStaticsize(int ItemType, int Size) +{ + m_SnapshotDelta.SetStaticsize(ItemType, Size); +} + +static CServer *CreateServer() { return new CServer(); } + + +void HandleSigIntTerm(int Param) +{ + InterruptSignaled = 1; + + // Exit the next time a signal is received + signal(SIGINT, SIG_DFL); + signal(SIGTERM, SIG_DFL); +} + +int main(int argc, const char **argv) // ignore_convention +{ + cmdline_fix(&argc, &argv); +#if defined(CONF_FAMILY_WINDOWS) + for(int i = 1; i < argc; i++) // ignore_convention + { + if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention + { + ShowWindow(GetConsoleWindow(), SW_HIDE); + break; + } + } +#endif + + bool UseDefaultConfig = false; + for(int i = 1; i < argc; i++) // ignore_convention + { + if(str_comp("-d", argv[i]) == 0 || str_comp("--default", argv[i]) == 0) // ignore_convention + { + UseDefaultConfig = true; + break; + } + } + + if(secure_random_init() != 0) + { + dbg_msg("secure", "could not initialize secure RNG"); + return -1; + } + + signal(SIGINT, HandleSigIntTerm); + signal(SIGTERM, HandleSigIntTerm); + + CServer *pServer = CreateServer(); + IKernel *pKernel = IKernel::Create(); + + // create the components + int FlagMask = CFGFLAG_SERVER|CFGFLAG_ECON; + IEngine *pEngine = CreateEngine("Teeworlds_Server"); + IEngineMap *pEngineMap = CreateEngineMap(); + IMapChecker *pMapChecker = CreateMapChecker(); + IGameServer *pGameServer = CreateGameServer(); + IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON); + IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); + IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention + IConfigManager *pConfigManager = CreateConfigManager(); + + pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConfigManager->Values(), pConsole); + + { + bool RegisterFail = false; + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap)); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pMapChecker); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfigManager); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer)); + + if(RegisterFail) + return -1; + } + + pEngine->Init(); + pConfigManager->Init(FlagMask); + pConsole->Init(); + pEngineMasterServer->Init(); + pEngineMasterServer->Load(); + + pServer->InitInterfaces(pKernel); + if(!UseDefaultConfig) + { + // register all console commands + pServer->RegisterCommands(); + + // execute autoexec file + pConsole->ExecuteFile("autoexec.cfg"); + + // parse the command line arguments + if(argc > 1) // ignore_convention + pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + } + + // restore empty config strings to their defaults + pConfigManager->RestoreStrings(); + + pEngine->InitLogfile(); + + pServer->InitRconPasswordIfUnset(); + + // run the server + dbg_msg("server", "starting..."); + int Ret = pServer->Run(); + + // free + delete pServer; + delete pKernel; + delete pEngine; + delete pEngineMap; + delete pMapChecker; + delete pGameServer; + delete pConsole; + delete pEngineMasterServer; + delete pStorage; + delete pConfigManager; + + secure_random_uninit(); + cmdline_free(argc, argv); + return Ret; +} diff --git a/src/engine/server/server.h b/src/engine/server/server.h new file mode 100644 index 000000000..ac43b2eb6 --- /dev/null +++ b/src/engine/server/server.h @@ -0,0 +1,287 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_SERVER_H +#define ENGINE_SERVER_SERVER_H + +#include +#include + +class CSnapIDPool +{ + enum + { + MAX_IDS = 16*1024, + }; + + class CID + { + public: + short m_Next; + short m_State; // 0 = free, 1 = allocated, 2 = timed + int m_Timeout; + }; + + CID m_aIDs[MAX_IDS]; + + int m_FirstFree; + int m_FirstTimed; + int m_LastTimed; + int m_Usage; + int m_InUsage; + +public: + + CSnapIDPool(); + + void Reset(); + void RemoveFirstTimeout(); + int NewID(); + void TimeoutIDs(); + void FreeID(int ID); +}; + + +class CServerBan : public CNetBan +{ + class CServer *m_pServer; + + template int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + +public: + class CServer *Server() const { return m_pServer; } + + void InitServerBan(class IConsole *pConsole, class IStorage *pStorage, class CServer* pServer); + + virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); + virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); + + static void ConBanExt(class IConsole::IResult *pResult, void *pUser); +}; + + +class CServer : public IServer +{ + class IGameServer *m_pGameServer; + class CConfig *m_pConfig; + class IConsole *m_pConsole; + class IStorage *m_pStorage; +public: + class IGameServer *GameServer() { return m_pGameServer; } + class CConfig *Config() { return m_pConfig; } + class IConsole *Console() { return m_pConsole; } + class IStorage *Storage() { return m_pStorage; } + + enum + { + AUTHED_NO=0, + AUTHED_MOD, + AUTHED_ADMIN, + + MAX_RCONCMD_SEND=16, + MAX_MAPLISTENTRY_SEND = 32, + MIN_MAPLIST_CLIENTVERSION=0x0703, // todo 0.8: remove me + MAX_RCONCMD_RATIO=8, + }; + + struct CMapListEntry; + + class CClient + { + public: + + enum + { + STATE_EMPTY = 0, + STATE_AUTH, + STATE_CONNECTING, + STATE_CONNECTING_AS_SPEC, + STATE_READY, + STATE_INGAME, + + SNAPRATE_INIT=0, + SNAPRATE_FULL, + SNAPRATE_RECOVER + }; + + class CInput + { + public: + int m_aData[MAX_INPUT_SIZE]; + int m_GameTick; // the tick that was chosen for the input + }; + + // connection state info + int m_State; + int m_Latency; + int m_SnapRate; + + int m_LastAckedSnapshot; + int m_LastInputTick; + CSnapshotStorage m_Snapshots; + + CInput m_LatestInput; + CInput m_aInputs[200]; // TODO: handle input better + int m_CurrentInput; + + char m_aName[MAX_NAME_ARRAY_SIZE]; + char m_aClan[MAX_CLAN_ARRAY_SIZE]; + int m_Version; + int m_Country; + int m_Score; + int m_Authed; + int m_AuthTries; + + int m_MapChunk; + bool m_NoRconNote; + bool m_Quitting; + const IConsole::CCommandInfo *m_pRconCmdToSend; + const CMapListEntry *m_pMapListEntryToSend; + + void Reset(); + }; + + CClient m_aClients[MAX_CLIENTS]; + + CSnapshotDelta m_SnapshotDelta; + CSnapshotBuilder m_SnapshotBuilder; + CSnapIDPool m_IDPool; + CNetServer m_NetServer; + CEcon m_Econ; + CServerBan m_ServerBan; + + IEngineMap *m_pMap; + IMapChecker *m_pMapChecker; + + int64 m_GameStartTime; + bool m_RunServer; + bool m_MapReload; + int m_RconClientID; + int m_RconAuthLevel; + int m_PrintCBIndex; + char m_aShutdownReason[128]; + + // map + enum + { + MAP_CHUNK_SIZE=NET_MAX_PAYLOAD-NET_MAX_CHUNKHEADERSIZE-4, // msg type + }; + char m_aCurrentMap[64]; + SHA256_DIGEST m_CurrentMapSha256; + unsigned m_CurrentMapCrc; + unsigned char *m_pCurrentMapData; + int m_CurrentMapSize; + int m_MapChunksPerRequest; + + //maplist + struct CMapListEntry + { + CMapListEntry *m_pPrev; + CMapListEntry *m_pNext; + char m_aName[IConsole::TEMPMAP_NAME_LENGTH]; + }; + + CHeap *m_pMapListHeap; + CMapListEntry *m_pLastMapEntry; + CMapListEntry *m_pFirstMapEntry; + int m_NumMapEntries; + + int m_RconPasswordSet; + int m_GeneratedRconPassword; + + CDemoRecorder m_DemoRecorder; + CRegister m_Register; + + CServer(); + + virtual void SetClientName(int ClientID, const char *pName); + virtual void SetClientClan(int ClientID, char const *pClan); + virtual void SetClientCountry(int ClientID, int Country); + virtual void SetClientScore(int ClientID, int Score); + + void Kick(int ClientID, const char *pReason); + + void DemoRecorder_HandleAutoStart(); + bool DemoRecorder_IsRecording(); + + int64 TickStartTime(int Tick); + + int Init(); + + void InitRconPasswordIfUnset(); + + void SetRconCID(int ClientID); + bool IsAuthed(int ClientID) const; + bool IsBanned(int ClientID); + int GetClientInfo(int ClientID, CClientInfo *pInfo) const; + void GetClientAddr(int ClientID, char *pAddrStr, int Size) const; + int GetClientVersion(int ClientID) const; + const char *ClientName(int ClientID) const; + const char *ClientClan(int ClientID) const; + int ClientCountry(int ClientID) const; + bool ClientIngame(int ClientID) const; + + virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID); + + void DoSnapshot(); + + static int NewClientCallback(int ClientID, void *pUser); + static int DelClientCallback(int ClientID, const char *pReason, void *pUser); + + void SendMap(int ClientID); + void SendConnectionReady(int ClientID); + void SendRconLine(int ClientID, const char *pLine); + static void SendRconLineAuthed(const char *pLine, void *pUser, bool Highlighted); + + void SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID); + void SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID); + void UpdateClientRconCommands(); + void SendMapListEntryAdd(const CMapListEntry *pMapListEntry, int ClientID); + void SendMapListEntryRem(const CMapListEntry *pMapListEntry, int ClientID); + void UpdateClientMapListEntries(); + + void ProcessClientPacket(CNetChunk *pPacket); + + void SendServerInfo(int ClientID); + void GenerateServerInfo(CPacker *pPacker, int Token); + + void PumpNetwork(); + + virtual void ChangeMap(const char *pMap); + const char *GetMapName(); + int LoadMap(const char *pMapName); + + void InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, CConfig *pConfig, IConsole *pConsole); + void InitInterfaces(IKernel *pKernel); + int Run(); + void Free(); + + static int MapListEntryCallback(const char *pFilename, int IsDir, int DirType, void *pUser); + void InitMapList(); + + static void ConKick(IConsole::IResult *pResult, void *pUser); + static void ConStatus(IConsole::IResult *pResult, void *pUser); + static void ConShutdown(IConsole::IResult *pResult, void *pUser); + static void ConRecord(IConsole::IResult *pResult, void *pUser); + static void ConStopRecord(IConsole::IResult *pResult, void *pUser); + static void ConMapReload(IConsole::IResult *pResult, void *pUser); + static void ConSaveConfig(IConsole::IResult *pResult, void *pUser); + static void ConLogout(IConsole::IResult *pResult, void *pUser); + static void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainPlayerSlotsUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainMaxclientsUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainRconPasswordSet(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainMapUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + + void RegisterCommands(); + + + virtual int SnapNewID(); + virtual void SnapFreeID(int ID); + virtual void *SnapNewItem(int Type, int ID, int Size); + void SnapSetStaticsize(int ItemType, int Size); +}; + +#endif diff --git a/src/engine/shared/compression.cpp b/src/engine/shared/compression.cpp new file mode 100644 index 000000000..44b11f14d --- /dev/null +++ b/src/engine/shared/compression.cpp @@ -0,0 +1,100 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include "compression.h" + +// Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign +unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) +{ + *pDst = 0; + if(i < 0) + { + *pDst |= 0x40; // set sign bit + i = ~i; + } + + *pDst |= i & 0x3F; // pack 6bit into dst + i >>= 6; // discard 6 bits + while(i) + { + *pDst |= 0x80; // set extend bit + pDst++; + *pDst = i & 0x7F; // pack 7bit + i >>= 7; // discard 7 bits + } + + pDst++; + return pDst; +} + +const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut) +{ + const int Sign = (*pSrc >> 6) & 1; + *pInOut = *pSrc & 0x3F; + + do + { + if(!(*pSrc & 0x80)) + break; + pSrc++; + *pInOut |= (*pSrc & 0x7F) << 6; + + if(!(*pSrc & 0x80)) + break; + pSrc++; + *pInOut |= (*pSrc & 0x7F) << (6 + 7); + + if(!(*pSrc & 0x80)) + break; + pSrc++; + *pInOut |= (*pSrc & 0x7F) << (6 + 7 + 7); + + if(!(*pSrc & 0x80)) + break; + pSrc++; + *pInOut |= (*pSrc & 0x0F) << (6 + 7 + 7 + 7); + } while(false); + + pSrc++; + *pInOut ^= -Sign; // if(sign) *i = ~(*i) + return pSrc; +} + +long CVariableInt::Decompress(const void *pSrc_, int SrcSize, void *pDst_, int DstSize) +{ + dbg_assert(DstSize % sizeof(int) == 0, "invalid bounds"); + + const unsigned char *pSrc = (unsigned char *)pSrc_; + const unsigned char *pEnd = pSrc + SrcSize; + int *pDst = (int *)pDst_; + const int *pDstEnd = pDst + DstSize / sizeof(int); + while(pSrc < pEnd) + { + if(pDst >= pDstEnd) + return -1; + pSrc = CVariableInt::Unpack(pSrc, pDst); + pDst++; + } + return (long)((unsigned char *)pDst - (unsigned char *)pDst_); +} + +long CVariableInt::Compress(const void *pSrc_, int SrcSize, void *pDst_, int DstSize) +{ + dbg_assert(SrcSize % sizeof(int) == 0, "invalid bounds"); + + const int *pSrc = (int *)pSrc_; + unsigned char *pDst = (unsigned char *)pDst_; + const unsigned char *pDstEnd = pDst + DstSize; + SrcSize /= sizeof(int); + while(SrcSize) + { + if(pDstEnd - pDst <= MAX_BYTES_PACKED) + return -1; + pDst = CVariableInt::Pack(pDst, *pSrc); + SrcSize--; + pSrc++; + } + return (long)(pDst - (unsigned char *)pDst_); +} + diff --git a/src/engine/shared/compression.h b/src/engine/shared/compression.h new file mode 100644 index 000000000..f15615d6b --- /dev/null +++ b/src/engine/shared/compression.h @@ -0,0 +1,22 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_COMPRESSION_H +#define ENGINE_SHARED_COMPRESSION_H + +// variable int packing +class CVariableInt +{ +public: + enum + { + MAX_BYTES_PACKED = 5, // maximum number of bytes in a packed int + }; + + static unsigned char *Pack(unsigned char *pDst, int i); + static const unsigned char *Unpack(const unsigned char *pSrc, int *pInOut); + + static long Compress(const void *pSrc, int SrcSize, void *pDst, int DstSize); + static long Decompress(const void *pSrc, int SrcSize, void *pDst, int DstSize); +}; + +#endif diff --git a/src/engine/shared/config.cpp b/src/engine/shared/config.cpp new file mode 100644 index 000000000..f79e2b192 --- /dev/null +++ b/src/engine/shared/config.cpp @@ -0,0 +1,138 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include +#include +#include + + +void EscapeParam(char *pDst, const char *pSrc, int size) +{ + for(int i = 0; *pSrc && i < size - 1; ++i) + { + if(*pSrc == '"' || *pSrc == '\\') // escape \ and " + *pDst++ = '\\'; + *pDst++ = *pSrc++; + } + *pDst = 0; +} + +static void Con_SaveConfig(IConsole::IResult *pResult, void *pUserData) +{ + char aFilename[128]; + if(pResult->NumArguments()) + str_format(aFilename, sizeof(aFilename), "configs/%s.cfg", pResult->GetString(0)); + else + { + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "configs/config_%s.cfg", aDate); + } + ((CConfigManager *)pUserData)->Save(aFilename); +} + +CConfigManager::CConfigManager() +{ + m_pStorage = 0; + m_pConsole = 0; + m_ConfigFile = 0; + m_FlagMask = 0; + m_NumCallbacks = 0; +} + +void CConfigManager::Init(int FlagMask) +{ + m_pStorage = Kernel()->RequestInterface(); + m_pConsole = Kernel()->RequestInterface(); + m_FlagMask = FlagMask; + Reset(); + + if(m_pConsole) + m_pConsole->Register("save_config", "?s[file]", CFGFLAG_SERVER|CFGFLAG_CLIENT|CFGFLAG_STORE, Con_SaveConfig, this, "Save config to file"); +} + +void CConfigManager::Reset() +{ + #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) m_Values.m_##Name = def; + #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(m_Values.m_##Name, def, len); + #define MACRO_CONFIG_UTF8STR(Name,ScriptName,size,len,def,flags,desc) str_utf8_copy_num(m_Values.m_##Name, def, size, len); + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_UTF8STR +} + +void CConfigManager::RestoreStrings() +{ + #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) // nop + #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if(!m_Values.m_##Name[0] && def[0]) str_copy(m_Values.m_##Name, def, len); + #define MACRO_CONFIG_UTF8STR(Name,ScriptName,size,len,def,flags,desc) if(!m_Values.m_##Name[0] && def[0]) str_utf8_copy_num(m_Values.m_##Name, def, size, len); + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_UTF8STR +} + +void CConfigManager::Save(const char *pFilename) +{ + if(!m_pStorage) + return; + + if(!pFilename) + pFilename = SETTINGS_FILENAME ".cfg"; + m_ConfigFile = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + + if(!m_ConfigFile) + return; + + WriteLine("# Teeworlds " GAME_VERSION); + + char aLineBuf[1024*2]; + char aEscapeBuf[1024*2]; + + #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if(((flags)&(CFGFLAG_SAVE))&&((flags)&(m_FlagMask))&&(m_Values.m_##Name!=int(def))){ str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, m_Values.m_##Name); WriteLine(aLineBuf); } + #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if(((flags)&(CFGFLAG_SAVE))&&((flags)&(m_FlagMask)&&(str_comp(m_Values.m_##Name,def)))){ EscapeParam(aEscapeBuf, m_Values.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); } + #define MACRO_CONFIG_UTF8STR(Name,ScriptName,size,len,def,flags,desc) if(((flags)&(CFGFLAG_SAVE))&&((flags)&(m_FlagMask)&&(str_comp(m_Values.m_##Name,def)))){ EscapeParam(aEscapeBuf, m_Values.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); } + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_UTF8STR + + for(int i = 0; i < m_NumCallbacks; i++) + m_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData); + + io_close(m_ConfigFile); + + if(m_pConsole) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "saved config to '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "config", aBuf); + } +} + +void CConfigManager::RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) +{ + dbg_assert(m_NumCallbacks < MAX_CALLBACKS, "too many config callbacks"); + m_aCallbacks[m_NumCallbacks].m_pfnFunc = pfnFunc; + m_aCallbacks[m_NumCallbacks].m_pUserData = pUserData; + m_NumCallbacks++; +} + +void CConfigManager::WriteLine(const char *pLine) +{ + if(!m_ConfigFile) + return; + + io_write(m_ConfigFile, pLine, str_length(pLine)); + io_write_newline(m_ConfigFile); +} + +IConfigManager *CreateConfigManager() { return new CConfigManager; } diff --git a/src/engine/shared/config.h b/src/engine/shared/config.h new file mode 100644 index 000000000..e1a618820 --- /dev/null +++ b/src/engine/shared/config.h @@ -0,0 +1,69 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONFIG_H +#define ENGINE_SHARED_CONFIG_H + +#include +#include "protocol.h" + +class CConfig +{ +public: + #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name; + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore + #define MACRO_CONFIG_UTF8STR(Name,ScriptName,Size,Len,Def,Save,Desc) char m_##Name[Size]; // Flawfinder: ignore + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_UTF8STR +}; + +enum +{ + CFGFLAG_SAVE=1, + CFGFLAG_CLIENT=2, + CFGFLAG_SERVER=4, + CFGFLAG_STORE=8, + CFGFLAG_MASTER=16, + CFGFLAG_ECON=32, + CFGFLAG_BASICACCESS=64, +}; + +class CConfigManager : public IConfigManager +{ + enum + { + MAX_CALLBACKS = 16 + }; + + struct CCallback + { + SAVECALLBACKFUNC m_pfnFunc; + void *m_pUserData; + }; + + class IStorage *m_pStorage; + class IConsole *m_pConsole; + IOHANDLE m_ConfigFile; + int m_FlagMask; + CCallback m_aCallbacks[MAX_CALLBACKS]; + int m_NumCallbacks; + CConfig m_Values; + +public: + CConfigManager(); + + virtual void Init(int FlagMask); + virtual void Reset(); + virtual void RestoreStrings(); + virtual void Save(const char *pFilename); + virtual CConfig *Values() { return &m_Values; } + + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData); + + virtual void WriteLine(const char *pLine); +}; + +#endif diff --git a/src/engine/shared/config_variables.h b/src/engine/shared/config_variables.h new file mode 100644 index 000000000..6e6cfd802 --- /dev/null +++ b/src/engine/shared/config_variables.h @@ -0,0 +1,120 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONFIG_VARIABLES_H +#define ENGINE_SHARED_CONFIG_VARIABLES_H +#undef ENGINE_SHARED_CONFIG_VARIABLES_H // this file will be included several times + +// TODO: remove this +#include "././game/variables.h" + + +MACRO_CONFIG_UTF8STR(PlayerName, player_name, MAX_NAME_ARRAY_SIZE, MAX_NAME_LENGTH, "nameless tee", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Name of the player") +MACRO_CONFIG_UTF8STR(PlayerClan, player_clan, MAX_CLAN_ARRAY_SIZE, MAX_CLAN_LENGTH, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clan of the player") +MACRO_CONFIG_INT(PlayerCountry, player_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Country of the player") +MACRO_CONFIG_STR(Password, password, 32, "", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Password to the server") +MACRO_CONFIG_STR(Logfile, logfile, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Filename to log all output to") +MACRO_CONFIG_INT(LogfileTimestamp, logfile_timestamp, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Add a time stamp to the log file's name") +MACRO_CONFIG_INT(ConsoleOutputLevel, console_output_level, 0, 0, 2, CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Adjusts the amount of information in the console") +MACRO_CONFIG_INT(ShowConsoleWindow, show_console_window, 1, 0, 3, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show console window (0 = never, 1 = debug, 2 = release, 3 = always") + +MACRO_CONFIG_INT(ClCpuThrottle, cl_cpu_throttle, 0, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Throttles the main thread") +MACRO_CONFIG_INT(ClEditor, cl_editor, 0, 0, 1, CFGFLAG_CLIENT, "View the editor") +MACRO_CONFIG_INT(ClLoadCountryFlags, cl_load_country_flags, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Load and show country flags") + +MACRO_CONFIG_INT(ClAutoDemoRecord, cl_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically record demos") +MACRO_CONFIG_INT(ClAutoDemoMax, cl_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically recorded demos (0 = no limit)") +MACRO_CONFIG_INT(ClAutoScreenshot, cl_auto_screenshot, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically take game over screenshot") +MACRO_CONFIG_INT(ClAutoStatScreenshot, cl_auto_statscreenshot, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically take screenshot of game statistics") +MACRO_CONFIG_INT(ClAutoScreenshotMax, cl_auto_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically created screenshots (0 = no limit)") + +MACRO_CONFIG_INT(ClShowServerBroadcast, cl_show_server_broadcast, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show server broadcast") +MACRO_CONFIG_INT(ClColoredBroadcast, cl_colored_broadcast, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable colored server broadcasts") + +MACRO_CONFIG_INT(ClSaveServerPasswords, cl_save_server_passwords, 1, 0, 2, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Save server passwords (0 = never, 1 = only favorites, 2 = all servers)") + +MACRO_CONFIG_STR(BrFilterString, br_filter_string, 25, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server browser filtering string") + +MACRO_CONFIG_INT(BrSort, br_sort, 4, 0, 256, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sort criterion for the server browser") +MACRO_CONFIG_INT(BrSortOrder, br_sort_order, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sort order in the server browser") +MACRO_CONFIG_INT(BrMaxRequests, br_max_requests, 25, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Number of requests to use when refreshing server browser") + +MACRO_CONFIG_INT(BrDemoSort, br_demo_sort, 0, 0, 2, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sort criterion for the demo browser") +MACRO_CONFIG_INT(BrDemoSortOrder, br_demo_sort_order, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sort order in the demo browser") + +MACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 128, 32768, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound buffer size") +MACRO_CONFIG_INT(SndRate, snd_rate, 48000, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound mixing rate") +MACRO_CONFIG_INT(SndEnable, snd_enable, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable sounds") +MACRO_CONFIG_INT(SndInit, snd_init, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Initialize sound systems") +MACRO_CONFIG_INT(SndMusic, snd_enable_music, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Play background music") +MACRO_CONFIG_INT(SndVolume, snd_volume, 100, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound volume") +MACRO_CONFIG_INT(SndNonactiveMute, snd_nonactive_mute, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mute the application when not active") +MACRO_CONFIG_INT(SndAsyncLoading, snd_async_loading, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Load sound files threaded") + +MACRO_CONFIG_INT(GfxScreen, gfx_screen, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen index") +MACRO_CONFIG_INT(GfxScreenWidth, gfx_screen_width, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution width") +MACRO_CONFIG_INT(GfxScreenHeight, gfx_screen_height, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution height") +MACRO_CONFIG_INT(GfxBorderless, gfx_borderless, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Borderless window (not to be used with fullscreen)") +MACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Fullscreen") +MACRO_CONFIG_INT(GfxClear, gfx_clear, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clear screen before rendering") +MACRO_CONFIG_INT(GfxVsync, gfx_vsync, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Vertical sync") +MACRO_CONFIG_INT(GfxDisplayAllModes, gfx_display_all_modes, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "List non-supported display modes") +MACRO_CONFIG_INT(GfxHighdpi, gfx_highdpi, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use high dpi mode if available") +MACRO_CONFIG_INT(GfxTextureCompression, gfx_texture_compression, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use texture compression") +MACRO_CONFIG_INT(GfxHighDetail, gfx_high_detail, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "High detail") +MACRO_CONFIG_INT(GfxTextureQuality, gfx_texture_quality, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Don't scale textures down") +MACRO_CONFIG_INT(GfxFsaaSamples, gfx_fsaa_samples, 0, 0, 16, CFGFLAG_SAVE|CFGFLAG_CLIENT, "FSAA Samples") +MACRO_CONFIG_INT(GfxFinish, gfx_finish, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Wait till the gpu finished the current frame before starting the new one") +MACRO_CONFIG_INT(GfxAsyncRender, gfx_asyncrender, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Do rendering asynchronously") +MACRO_CONFIG_INT(GfxMaxFps, gfx_maxfps, 144, 30, 2000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum fps (when limit fps is enabled)") +MACRO_CONFIG_INT(GfxLimitFps, gfx_limitfps, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Limit fps") +MACRO_CONFIG_INT(GfxUseX11XRandRWM, gfx_use_x11xrandr_wm, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Let SDL use the X11 XRandR window manager") + +MACRO_CONFIG_INT(InpGrab, inp_grab, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Disable OS mouse settings such as mouse acceleration, use raw mouse input mode") +MACRO_CONFIG_INT(InpMousesens, inp_mousesens, 100, 1, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Ingame mouse sensitivity") + +MACRO_CONFIG_INT(JoystickEnable , joystick_enable, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable joystick") +MACRO_CONFIG_STR(JoystickGUID, joystick_guid, 34, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Joystick GUID which uniquely identifies the active joystick") +MACRO_CONFIG_INT(JoystickAbsolute, joystick_absolute, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable absolute joystick aiming ingame") +MACRO_CONFIG_INT(JoystickSens, joystick_sens, 100, 1, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Ingame joystick sensitivity") +MACRO_CONFIG_INT(JoystickX, joystick_x, 0, 0, 12, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Joystick axis that controls X axis of cursor") +MACRO_CONFIG_INT(JoystickY, joystick_y, 1, 0, 12, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Joystick axis that controls Y axis of cursor") +MACRO_CONFIG_INT(JoystickTolerance, joystick_tolerance, 5, 0, 50, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Joystick axis tolerance to account for jitter") + +MACRO_CONFIG_STR(SvName, sv_name, 128, "unnamed server", CFGFLAG_SAVE|CFGFLAG_SERVER, "Server name") +MACRO_CONFIG_STR(SvHostname, sv_hostname, 128, "", CFGFLAG_SAVE|CFGFLAG_SERVER, "Server hostname") +MACRO_CONFIG_STR(Bindaddr, bindaddr, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER|CFGFLAG_MASTER, "Address to bind the client/server to") +MACRO_CONFIG_INT(SvPort, sv_port, 8303, 0, 0, CFGFLAG_SAVE|CFGFLAG_SERVER, "Port to use for the server") +MACRO_CONFIG_INT(SvExternalPort, sv_external_port, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_SERVER, "External port to report to the master servers") +MACRO_CONFIG_STR(SvMap, sv_map, 128, "dm1", CFGFLAG_SAVE|CFGFLAG_SERVER, "Map to use on the server") +MACRO_CONFIG_INT(SvMaxClients, sv_max_clients, 8, 1, MAX_CLIENTS, CFGFLAG_SAVE|CFGFLAG_SERVER, "Maximum number of clients that are allowed on a server") +MACRO_CONFIG_INT(SvMaxClientsPerIP, sv_max_clients_per_ip, 4, 1, MAX_CLIENTS, CFGFLAG_SAVE|CFGFLAG_SERVER, "Maximum number of clients with the same IP that can connect to the server") +MACRO_CONFIG_INT(SvMapDownloadSpeed, sv_map_download_speed, 8, 1, 16, CFGFLAG_SAVE|CFGFLAG_SERVER, "Number of map data packages a client gets on each request") +MACRO_CONFIG_INT(SvHighBandwidth, sv_high_bandwidth, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Use high bandwidth mode. Doubles the bandwidth required for the server. LAN use only") +MACRO_CONFIG_INT(SvRegister, sv_register, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Register server with master server for public listing") +MACRO_CONFIG_STR(SvRconPassword, sv_rcon_password, 32, "", CFGFLAG_SAVE|CFGFLAG_SERVER, "Remote console password (full access)") +MACRO_CONFIG_STR(SvRconModPassword, sv_rcon_mod_password, 32, "", CFGFLAG_SAVE|CFGFLAG_SERVER, "Remote console password for moderators (limited access)") +MACRO_CONFIG_INT(SvRconMaxTries, sv_rcon_max_tries, 3, 0, 100, CFGFLAG_SAVE|CFGFLAG_SERVER, "Maximum number of tries for remote console authentication") +MACRO_CONFIG_INT(SvRconBantime, sv_rcon_bantime, 5, 0, 1440, CFGFLAG_SAVE|CFGFLAG_SERVER, "The time a client gets banned if remote console authentication fails. 0 makes it just use kick") +MACRO_CONFIG_INT(SvAutoDemoRecord, sv_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Automatically record demos") +MACRO_CONFIG_INT(SvAutoDemoMax, sv_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Maximum number of automatically recorded demos (0 = no limit)") +MACRO_CONFIG_STR(SvMaplist, sv_maplist, 32, "all", CFGFLAG_SAVE|CFGFLAG_SERVER, "Maplist for authed clients (none, standard, all)") + +MACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, "localhost", CFGFLAG_SAVE|CFGFLAG_ECON, "Address to bind the external console to. Anything but 'localhost' is dangerous") +MACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_ECON, "Port to use for the external console") +MACRO_CONFIG_STR(EcPassword, ec_password, 32, "", CFGFLAG_SAVE|CFGFLAG_ECON, "External console password") +MACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_SAVE|CFGFLAG_ECON, "The time a client gets banned if econ authentication fails. 0 just closes the connection") +MACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_SAVE|CFGFLAG_ECON, "Time in seconds before the the econ authentification times out") +MACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_SAVE|CFGFLAG_ECON, "Adjusts the amount of information in the external console") + +MACRO_CONFIG_INT(NetTcpAbortOnClose, net_tcp_abort_on_close, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER|CFGFLAG_ECON, "Aborts tcp connection on close") + +MACRO_CONFIG_INT(Debug, debug, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Debug mode") +MACRO_CONFIG_INT(DbgStress, dbg_stress, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress systems") +MACRO_CONFIG_INT(DbgStressNetwork, dbg_stress_network, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress network") +MACRO_CONFIG_INT(DbgPref, dbg_pref, 0, 0, 1, CFGFLAG_SERVER, "Performance outputs") +MACRO_CONFIG_INT(DbgGraphs, dbg_graphs, 0, 0, 1, CFGFLAG_CLIENT, "Performance graphs") +MACRO_CONFIG_INT(DbgHitch, dbg_hitch, 0, 0, 0, CFGFLAG_SERVER, "Hitch warnings") +MACRO_CONFIG_STR(DbgStressServer, dbg_stress_server, 32, "localhost", CFGFLAG_CLIENT, "Server to stress") +MACRO_CONFIG_INT(DbgResizable, dbg_resizable, 0, 0, 0, CFGFLAG_CLIENT, "Enables window resizing") + +#endif diff --git a/src/engine/shared/console.cpp b/src/engine/shared/console.cpp new file mode 100644 index 000000000..8ecab64b4 --- /dev/null +++ b/src/engine/shared/console.cpp @@ -0,0 +1,1159 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include + +#include +#include + +#include "config.h" +#include "console.h" +#include "linereader.h" + +// todo: rework this + +const char *CConsole::CResult::GetString(unsigned Index) +{ + if (Index >= m_NumArgs) + return ""; + return m_apArgs[Index]; +} + +int CConsole::CResult::GetInteger(unsigned Index) +{ + if (Index >= m_NumArgs) + return 0; + return str_toint(m_apArgs[Index]); +} + +float CConsole::CResult::GetFloat(unsigned Index) +{ + if (Index >= m_NumArgs) + return 0.0f; + return str_tofloat(m_apArgs[Index]); +} + +const IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLevel, int FlagMask) const +{ + const CCommand *pInfo = m_pNext; + while(pInfo) + { + if(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel) + break; + pInfo = pInfo->m_pNext; + } + return pInfo; +} + +const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int FlagMask) const +{ + for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel) + return pCommand; + } + + return 0; +} + +// the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces + + +int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) +{ + char *pStr; + int Len = sizeof(pResult->m_aStringStorage); + if(Length < Len) + Len = Length; + + str_copy(pResult->m_aStringStorage, pString, Len); + pStr = pResult->m_aStringStorage; + + // get command + pStr = str_skip_whitespaces(pStr); + pResult->m_pCommand = pStr; + pStr = str_skip_to_whitespace(pStr); + + if(*pStr) + { + pStr[0] = 0; + pStr++; + } + + pResult->m_pArgsStart = pStr; + return 0; +} + +bool CConsole::ArgStringIsValid(const char *pFormat) +{ + char Command = *pFormat; + bool Valid = true; + bool Last = false; + + while(Valid) + { + if(!Command) + break; + + if(Last && *pFormat) + return false; + + if(Command == '?') + { + if(!pFormat[1]) + return false; + } + else + { + if(Command == 'i' || Command == 'f' || Command == 's') + ; + else if(Command == 'r') + Last = true; + else + return false; + } + + Valid = !NextParam(&Command, pFormat); + } + + return Valid; +} + +int CConsole::ParseArgs(CResult *pResult, const char *pFormat) +{ + char Command = *pFormat; + char *pStr; + int Optional = 0; + int Error = 0; + + pStr = pResult->m_pArgsStart; + + while(!Error) + { + if(!Command) + break; + + if(Command == '?') + Optional = 1; + else + { + pStr = str_skip_whitespaces(pStr); + + if(!(*pStr)) // error, non optional command needs value + { + if(!Optional) + { + Error = 1; + } + break; + } + + // add token + if(*pStr == '"') + { + char *pDst; + pStr++; + pResult->AddArgument(pStr); + + pDst = pStr; // we might have to process escape data + while(1) + { + if(pStr[0] == '"') + break; + else if(pStr[0] == '\\') + { + if(pStr[1] == '\\') + pStr++; // skip due to escape + else if(pStr[1] == '"') + pStr++; // skip due to escape + } + else if(pStr[0] == 0) + return 1; // return error + + *pDst = *pStr; + pDst++; + pStr++; + } + + // write null termination + *pDst = 0; + + + pStr++; + } + else + { + pResult->AddArgument(pStr); + + if(Command == 'r') // rest of the string + { + str_utf8_trim_whitespaces_right(pStr); + break; + } + else if(Command == 'i') // validate int + pStr = str_skip_to_whitespace(pStr); + else if(Command == 'f') // validate float + pStr = str_skip_to_whitespace(pStr); + else if(Command == 's') // validate string + pStr = str_skip_to_whitespace(pStr); + + if(pStr[0] != 0) // check for end of string + { + pStr[0] = 0; + pStr++; + } + } + } + + // fetch next command + Error = NextParam(&Command, pFormat); + } + + return Error; +} + +bool CConsole::NextParam(char *pNext, const char *&pFormat) +{ + if(*pFormat) + { + pFormat++; + + if(*pFormat == '[') + { + // skip bracket contents + pFormat += str_span(pFormat, "]"); + if(!*pFormat) + return true; + + // skip ']' + pFormat++; + } + + // skip space if there is one + pFormat = str_skip_whitespaces_const(pFormat); + } + *pNext = *pFormat; + return false; +} + +int CConsole::ParseCommandArgs(const char *pArgs, const char *pFormat, FCommandCallback pfnCallback, void *pContext) +{ + CResult Result; + str_copy(Result.m_aStringStorage, pArgs, sizeof(Result.m_aStringStorage)); + Result.m_pArgsStart = Result.m_aStringStorage; + + int Error = ParseArgs(&Result, pFormat); + if(Error) + return Error; + + if(pfnCallback) + pfnCallback(&Result, pContext); + + return 0; +} + +int CConsole::RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) +{ + if(m_NumPrintCB == MAX_PRINT_CB) + return -1; + + m_aPrintCB[m_NumPrintCB].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); + m_aPrintCB[m_NumPrintCB].m_pfnPrintCallback = pfnPrintCallback; + m_aPrintCB[m_NumPrintCB].m_pPrintCallbackUserdata = pUserData; + return m_NumPrintCB++; +} + +void CConsole::SetPrintOutputLevel(int Index, int OutputLevel) +{ + if(Index >= 0 && Index < MAX_PRINT_CB) + m_aPrintCB[Index].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); +} + +void CConsole::Print(int Level, const char *pFrom, const char *pStr, bool Highlighted) +{ + char aTimeBuf[80]; + str_timestamp_format(aTimeBuf, sizeof(aTimeBuf), FORMAT_TIME); + + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "[%s][%s]: %s", aTimeBuf, pFrom, pStr); + dbg_msg(pFrom ,"%s", pStr); + for(int i = 0; i < m_NumPrintCB; ++i) + { + if(Level <= m_aPrintCB[i].m_OutputLevel && m_aPrintCB[i].m_pfnPrintCallback) + { + m_aPrintCB[i].m_pfnPrintCallback(aBuf, m_aPrintCB[i].m_pPrintCallbackUserdata, Highlighted); + } + } +} + +bool CConsole::LineIsValid(const char *pStr) +{ + if(!pStr) + return false; + + // Comments and empty lines are valid commands + if(*pStr == '#' || *pStr == '\0') + return true; + + do + { + CResult Result; + const char *pEnd = pStr; + const char *pNextPart = 0; + int InString = 0; + + while(*pEnd) + { + if(*pEnd == '"') + InString ^= 1; + else if(*pEnd == '\\') // escape sequences + { + if(pEnd[1] == '"') + pEnd++; + } + else if(!InString) + { + if(*pEnd == ';') // command separator + { + pNextPart = pEnd+1; + break; + } + else if(*pEnd == '#') // comment, no need to do anything more + break; + } + + pEnd++; + } + + if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) + return false; + + CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); + if(!pCommand || ParseArgs(&Result, pCommand->m_pParams)) + return false; + + pStr = pNextPart; + } + while(pStr && *pStr); + + return true; +} + +void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) +{ + while(pStr && *pStr) + { + CResult Result; + const char *pEnd = pStr; + const char *pNextPart = 0; + int InString = 0; + + while(*pEnd) + { + if(*pEnd == '"') + InString ^= 1; + else if(*pEnd == '\\') // escape sequences + { + if(pEnd[1] == '"') + pEnd++; + } + else if(!InString) + { + if(*pEnd == ';') // command separator + { + pNextPart = pEnd+1; + break; + } + else if(*pEnd == '#') // comment, no need to do anything more + break; + } + + pEnd++; + } + + if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) + return; + + if(!*Result.m_pCommand) + return; + + CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); + + if(pCommand) + { + if(pCommand->GetAccessLevel() >= m_AccessLevel) + { + int IsStrokeCommand = 0; + if(Result.m_pCommand[0] == '+') + { + // insert the stroke direction token + Result.AddArgument(m_paStrokeStr[Stroke]); + IsStrokeCommand = 1; + } + + if(Stroke || IsStrokeCommand) + { + if(ParseArgs(&Result, pCommand->m_pParams)) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Invalid arguments... Usage: %s %s", pCommand->m_pName, pCommand->m_pParams); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + else if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE) + { + m_ExecutionQueue.AddEntry(); + m_ExecutionQueue.m_pLast->m_pCommand = pCommand; + m_ExecutionQueue.m_pLast->m_Result = Result; + } + else + pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); + } + } + else if(Stroke) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Access for command %s denied.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + } + else if(Stroke) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "No such command: %s.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + + pStr = pNextPart; + } +} + +int CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) +{ + int Index = 0; + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp && str_find_nocase(pCommand->m_pName, pStr)) + { + pfnCallback(Index, pCommand->m_pName, pUser); + Index++; + } + } + return Index; +} + +int CConsole::PossibleMaps(const char *pStr, FPossibleCallback pfnCallback, void *pUser) +{ + int Index = 0; + for(CMapListEntryTemp *pMapEntry = m_pFirstMapEntry; pMapEntry; pMapEntry = pMapEntry->m_pNext) + { + if(str_find_nocase(pMapEntry->m_aName, pStr)) + { + pfnCallback(Index, pMapEntry->m_aName, pUser); + Index++; + } + } + return Index; +} + +CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) +{ + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && str_comp_nocase(pCommand->m_pName, pName) == 0) + { + return pCommand; + } + } + + return 0x0; +} + +void CConsole::ExecuteLine(const char *pStr) +{ + CConsole::ExecuteLineStroked(1, pStr); // press it + CConsole::ExecuteLineStroked(0, pStr); // then release it +} + +void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask) +{ + int Temp = m_FlagMask; + m_FlagMask = FlagMask; + ExecuteLine(pStr); + m_FlagMask = Temp; +} + + +bool CConsole::ExecuteFile(const char *pFilename) +{ + // make sure that this isn't being executed already + for(CExecFile *pCur = m_pFirstExec; pCur; pCur = pCur->m_pPrev) + if(str_comp(pFilename, pCur->m_pFilename) == 0) + return false; + + if(!m_pStorage) + return false; + + // push this one to the stack + CExecFile ThisFile; + CExecFile *pPrev = m_pFirstExec; + ThisFile.m_pFilename = pFilename; + ThisFile.m_pPrev = m_pFirstExec; + m_pFirstExec = &ThisFile; + + // exec the file + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ | IOFLAG_SKIP_BOM, IStorage::TYPE_ALL); + + char aBuf[256]; + if(File) + { + str_format(aBuf, sizeof(aBuf), "executing '%s'", pFilename); + Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + + CLineReader LineReader; + LineReader.Init(File); + const char *pLine; + while((pLine = LineReader.Get())) + ExecuteLine(pLine); + + io_close(File); + } + else + { + str_format(aBuf, sizeof(aBuf), "failed to open '%s'", pFilename); + Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + bool AbsHeur = false; + AbsHeur = AbsHeur || (pFilename[0] == '/' || pFilename[0] == '\\'); + AbsHeur = AbsHeur || (pFilename[0] && pFilename[1] == ':' && (pFilename[2] == '/' || pFilename[2] == '\\')); + if(AbsHeur) + { + Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", "Info: only relative paths starting from the ones you specify in 'storage.cfg' are allowed"); + } + } + + m_pFirstExec = pPrev; + return (bool)File; +} + +void CConsole::Con_Echo(IResult *pResult, void *pUserData) +{ + ((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0)); +} + +void CConsole::Con_Exec(IResult *pResult, void *pUserData) +{ + ((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0)); +} + +void CConsole::ConModCommandAccess(IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast(pUser); + char aBuf[128]; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), CFGFLAG_SERVER); + if(pCommand) + { + if(pResult->NumArguments() == 2) + { + pCommand->SetAccessLevel(pResult->GetInteger(1)); + str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); + } + else + str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); + + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CConsole::ConModCommandStatus(IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast(pUser); + char aBuf[240]; + mem_zero(aBuf, sizeof(aBuf)); + int Used = 0; + + for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() == ACCESS_LEVEL_MOD) + { + int Length = str_length(pCommand->m_pName); + if(Used + Length + 2 < (int)(sizeof(aBuf))) + { + if(Used > 0) + { + Used += 2; + str_append(aBuf, ", ", sizeof(aBuf)); + } + str_append(aBuf, pCommand->m_pName, sizeof(aBuf)); + Used += Length; + } + else + { + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + mem_zero(aBuf, sizeof(aBuf)); + str_copy(aBuf, pCommand->m_pName, sizeof(aBuf)); + Used = Length; + } + } + } + if(Used > 0) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +struct CIntVariableData +{ + IConsole *m_pConsole; + int *m_pVariable; + int m_Min; + int m_Max; +}; + +struct CStrVariableData +{ + IConsole *m_pConsole; + char *m_pStr; + int m_MaxSize; + int m_Length; +}; + +static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData) +{ + CIntVariableData *pData = (CIntVariableData *)pUserData; + + if(pResult->NumArguments()) + { + int Val = pResult->GetInteger(0); + + // do clamping + if(pData->m_Min != pData->m_Max) + { + if (Val < pData->m_Min) + Val = pData->m_Min; + if (pData->m_Max != 0 && Val > pData->m_Max) + Val = pData->m_Max; + } + + *(pData->m_pVariable) = Val; + } + else + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "Value: %d", *(pData->m_pVariable)); + pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + pResult->m_Value = *(pData->m_pVariable); + } +} + +static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData) +{ + CStrVariableData *pData = (CStrVariableData *)pUserData; + + if(pResult->NumArguments()) + { + const char *pString = pResult->GetString(0); + if(!str_utf8_check(pString)) + { + char Temp[4]; + int Length = 0; + while(*pString) + { + int Size = str_utf8_encode(Temp, static_cast(*pString++)); + if(Length+Size < pData->m_MaxSize) + { + mem_copy(pData->m_pStr+Length, &Temp, Size); + Length += Size; + } + else + break; + } + pData->m_pStr[Length] = 0; + } + else + str_utf8_copy_num(pData->m_pStr, pString, pData->m_MaxSize, pData->m_Length); + } + else + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "Value: %s", pData->m_pStr); + pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_copy(pResult->m_aValue, pData->m_pStr, sizeof(pResult->m_aValue)); + } +} + +void CConsole::TraverseChain(FCommandCallback *ppfnCallback, void **ppUserData) +{ + while(*ppfnCallback == Con_Chain) + { + CChain *pChainInfo = static_cast(*ppUserData); + *ppfnCallback = pChainInfo->m_pfnCallback; + *ppUserData = pChainInfo->m_pCallbackUserData; + } +} + +void CConsole::Con_EvalIf(IResult *pResult, void *pUserData) +{ + CConsole *pConsole = static_cast(pUserData); + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask); + char aBuf[128]; + if(!pCommand) + { + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + return; + } + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + void *pCallbackUserData = pCommand->m_pUserData; + pConsole->TraverseChain(&pfnCallback, &pCallbackUserData); + CResult Result; + pfnCallback(&Result, pCallbackUserData); + bool Condition = false; + if(pfnCallback == IntVariableCommand) + Condition = Result.m_Value == atoi(pResult->GetString(2)); + else + Condition = !str_comp_nocase(Result.m_aValue, pResult->GetString(2)); + if(!str_comp(pResult->GetString(1), "!=")) + Condition = !Condition; + else if(str_comp(pResult->GetString(1), "==") && pfnCallback == StrVariableCommand) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", "Error: invalid comperator for type string"); + else if(!str_comp(pResult->GetString(1), ">")) + Condition = Result.m_Value > atoi(pResult->GetString(2)); + else if(!str_comp(pResult->GetString(1), "<")) + Condition = Result.m_Value < atoi(pResult->GetString(2)); + else if(!str_comp(pResult->GetString(1), "<=")) + Condition = Result.m_Value <= atoi(pResult->GetString(2)); + else if(!str_comp(pResult->GetString(1), ">=")) + Condition = Result.m_Value >= atoi(pResult->GetString(2)); + else if(str_comp(pResult->GetString(1), "==")) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", "Error: invalid comperator for type integer"); + + if(pResult->NumArguments() > 4 && str_comp(pResult->GetString(4), "else")) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", "Error: expected else"); + + if(Condition) + pConsole->ExecuteLine(pResult->GetString(3)); + else if(pResult->NumArguments() == 6) + pConsole->ExecuteLine(pResult->GetString(5)); +} + +void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser) +{ + CConsole *pConsole = static_cast(pUser); + char aBuf[128] = {0}; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask); + if(pCommand) + { + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + void *pUserData = pCommand->m_pUserData; + pConsole->TraverseChain(&pfnCallback, &pUserData); + if(pfnCallback == IntVariableCommand) + { + CIntVariableData *pData = static_cast(pUserData); + int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1); + str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val); + pConsole->ExecuteLine(aBuf); + aBuf[0] = 0; + } + else + str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(0)); + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); + + if(aBuf[0]) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser) +{ + CConsole *pConsole = static_cast(pUser); + char aBuf[128] = {0}; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(1), pConsole->m_FlagMask); + if(pCommand) + { + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + void *pUserData = pCommand->m_pUserData; + pConsole->TraverseChain(&pfnCallback, &pUserData); + if(pfnCallback == IntVariableCommand) + { + int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2); + str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val); + pConsole->ExecuteLine(aBuf); + aBuf[0] = 0; + } + else + str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(1)); + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(1)); + + if(aBuf[0]) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +CConsole::CConsole(int FlagMask) +{ + m_FlagMask = FlagMask; + m_AccessLevel = ACCESS_LEVEL_ADMIN; + m_pRecycleList = 0; + m_TempCommands.Reset(); + m_StoreCommands = true; + m_paStrokeStr[0] = "0"; + m_paStrokeStr[1] = "1"; + m_pTempMapListHeap = 0; + m_pFirstMapEntry = 0; + m_pLastMapEntry = 0; + m_ExecutionQueue.Reset(); + m_pFirstCommand = 0; + m_pFirstExec = 0; + mem_zero(m_aPrintCB, sizeof(m_aPrintCB)); + m_NumPrintCB = 0; + + m_pConfig = 0; + m_pStorage = 0; + + // register some basic commands + Register("echo", "r[text]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, "Echo the text"); + Register("exec", "r[file]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); + Register("eval_if", "s[config] s[comparison] s[value] s[command] ?s[else] ?s[command]", CFGFLAG_SERVER|CFGFLAG_CLIENT|CFGFLAG_STORE, Con_EvalIf, this, "Execute command if condition is true"); + + Register("toggle", "s[config-option] i[value1] i[value2]", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value"); + Register("+toggle", "s[config-option] i[value1] i[value2]", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress"); + + Register("mod_command", "s[command] ?i[access-level]", CFGFLAG_SERVER, ConModCommandAccess, this, "Specify command accessibility for moderators"); + Register("mod_status", "", CFGFLAG_SERVER, ConModCommandStatus, this, "List all commands which are accessible for moderators"); +} + +CConsole::~CConsole() +{ + CCommand *pCommand = m_pFirstCommand; + while(pCommand) + { + CCommand *pNext = pCommand->m_pNext; + + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + void *pUserData = pCommand->m_pUserData; + while(pfnCallback == Con_Chain) + { + CChain *pChainInfo = static_cast(pUserData); + pfnCallback = pChainInfo->m_pfnCallback; + pUserData = pChainInfo->m_pCallbackUserData; + mem_free(pChainInfo); + } + + mem_free(pCommand); + + pCommand = pNext; + } + if(m_pTempMapListHeap) + { + delete m_pTempMapListHeap; + m_pTempMapListHeap = 0; + } +} + +void CConsole::Init() +{ + m_pConfig = Kernel()->RequestInterface()->Values(); + m_pStorage = Kernel()->RequestInterface(); + + // TODO: this should disappear + #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ + { \ + static CIntVariableData Data = { this, &m_pConfig->m_##Name, Min, Max }; \ + Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \ + } + + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ + { \ + static CStrVariableData Data = { this, m_pConfig->m_##Name, Len, Len }; \ + Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ + } + + #define MACRO_CONFIG_UTF8STR(Name,ScriptName,Size,Len,Def,Flags,Desc) \ + { \ + static CStrVariableData Data = { this, m_pConfig->m_##Name, Size, Len }; \ + Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ + } + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_UTF8STR +} + +void CConsole::ParseArguments(int NumArgs, const char **ppArguments) +{ + for(int i = 0; i < NumArgs; i++) + { + // check for scripts to execute + if(str_comp("-f", ppArguments[i]) == 0) + { + if(NumArgs - i > 1) + ExecuteFile(ppArguments[i+1]); + i++; + } + else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i]) || + !str_comp("-d", ppArguments[i]) || !str_comp("--default", ppArguments[i])) + { + // skip silent, default param + continue; + } + else + { + // search arguments for overrides + ExecuteLine(ppArguments[i]); + } + } +} + +void CConsole::AddCommandSorted(CCommand *pCommand) +{ + if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0) + { + if(m_pFirstCommand && m_pFirstCommand->m_pNext) + pCommand->m_pNext = m_pFirstCommand; + else + pCommand->m_pNext = 0; + m_pFirstCommand = pCommand; + } + else + { + for(CCommand *p = m_pFirstCommand; p; p = p->m_pNext) + { + if(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) <= 0) + { + pCommand->m_pNext = p->m_pNext; + p->m_pNext = pCommand; + break; + } + } + } +} + +void CConsole::Register(const char *pName, const char *pParams, + int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) +{ + CCommand *pCommand = FindCommand(pName, Flags); + bool DoAdd = false; + if(pCommand == 0) + { + pCommand = new(mem_alloc(sizeof(CCommand))) CCommand(Flags&CFGFLAG_BASICACCESS);; + DoAdd = true; + } + pCommand->m_pfnCallback = pfnFunc; + pCommand->m_pUserData = pUser; + + pCommand->m_pName = pName; + pCommand->m_pHelp = pHelp; + pCommand->m_pParams = pParams; + + pCommand->m_Flags = Flags; + pCommand->m_Temp = false; + + if(DoAdd) + AddCommandSorted(pCommand); +} + +void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) +{ + CCommand *pCommand; + if(m_pRecycleList) + { + pCommand = m_pRecycleList; + str_copy(const_cast(pCommand->m_pName), pName, TEMPCMD_NAME_LENGTH); + str_copy(const_cast(pCommand->m_pHelp), pHelp, TEMPCMD_HELP_LENGTH); + str_copy(const_cast(pCommand->m_pParams), pParams, TEMPCMD_PARAMS_LENGTH); + + m_pRecycleList = m_pRecycleList->m_pNext; + } + else + { + pCommand = new(m_TempCommands.Allocate(sizeof(CCommand))) CCommand(false); + char *pMem = static_cast(m_TempCommands.Allocate(TEMPCMD_NAME_LENGTH)); + str_copy(pMem, pName, TEMPCMD_NAME_LENGTH); + pCommand->m_pName = pMem; + pMem = static_cast(m_TempCommands.Allocate(TEMPCMD_HELP_LENGTH)); + str_copy(pMem, pHelp, TEMPCMD_HELP_LENGTH); + pCommand->m_pHelp = pMem; + pMem = static_cast(m_TempCommands.Allocate(TEMPCMD_PARAMS_LENGTH)); + str_copy(pMem, pParams, TEMPCMD_PARAMS_LENGTH); + pCommand->m_pParams = pMem; + } + + pCommand->m_pfnCallback = 0; + pCommand->m_pUserData = 0; + pCommand->m_Flags = Flags; + pCommand->m_Temp = true; + + AddCommandSorted(pCommand); +} + +void CConsole::DeregisterTemp(const char *pName) +{ + if(!m_pFirstCommand) + return; + + CCommand *pRemoved = 0; + + // remove temp entry from command list + if(m_pFirstCommand->m_Temp && str_comp(m_pFirstCommand->m_pName, pName) == 0) + { + pRemoved = m_pFirstCommand; + m_pFirstCommand = m_pFirstCommand->m_pNext; + } + else + { + for(CCommand *pCommand = m_pFirstCommand; pCommand->m_pNext; pCommand = pCommand->m_pNext) + if(pCommand->m_pNext->m_Temp && str_comp(pCommand->m_pNext->m_pName, pName) == 0) + { + pRemoved = pCommand->m_pNext; + pCommand->m_pNext = pCommand->m_pNext->m_pNext; + break; + } + } + + // add to recycle list + if(pRemoved) + { + pRemoved->m_pNext = m_pRecycleList; + m_pRecycleList = pRemoved; + } +} + +void CConsole::DeregisterTempAll() +{ + // set non temp as first one + for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext); + + // remove temp entries from command list + for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext) + { + CCommand *pNext = pCommand->m_pNext; + if(pNext->m_Temp) + { + for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext); + pCommand->m_pNext = pNext; + } + } + + m_TempCommands.Reset(); + m_pRecycleList = 0; +} + +void CConsole::RegisterTempMap(const char *pName) +{ + if(!m_pTempMapListHeap) + m_pTempMapListHeap = new CHeap(); + CMapListEntryTemp *pEntry = (CMapListEntryTemp *)m_pTempMapListHeap->Allocate(sizeof(CMapListEntryTemp)); + pEntry->m_pNext = 0; + pEntry->m_pPrev = m_pLastMapEntry; + if(pEntry->m_pPrev) + pEntry->m_pPrev->m_pNext = pEntry; + m_pLastMapEntry = pEntry; + if(!m_pFirstMapEntry) + m_pFirstMapEntry = pEntry; + str_copy(pEntry->m_aName, pName, TEMPMAP_NAME_LENGTH); +} + +void CConsole::DeregisterTempMap(const char *pName) +{ + if(!m_pFirstMapEntry) + return; + + CHeap *pNewTempMapListHeap = new CHeap(); + CMapListEntryTemp *pNewFirstEntry = 0; + CMapListEntryTemp *pNewLastEntry = 0; + + for(CMapListEntryTemp *pSrc = m_pFirstMapEntry; pSrc; pSrc = pSrc->m_pNext) + { + if(str_comp_nocase(pName, pSrc->m_aName) == 0) + continue; + + CMapListEntryTemp *pDst = (CMapListEntryTemp *)pNewTempMapListHeap->Allocate(sizeof(CMapListEntryTemp)); + pDst->m_pNext = 0; + pDst->m_pPrev = m_pLastMapEntry; + if(pDst->m_pPrev) + pDst->m_pPrev->m_pNext = pDst; + m_pLastMapEntry = pDst; + if(!m_pFirstMapEntry) + m_pFirstMapEntry = pDst; + + str_copy(pDst->m_aName, pSrc->m_aName, TEMPMAP_NAME_LENGTH); + } + + delete m_pTempMapListHeap; + m_pTempMapListHeap = pNewTempMapListHeap; + m_pFirstMapEntry = pNewFirstEntry; + m_pLastMapEntry = pNewLastEntry; +} + +void CConsole::DeregisterTempMapAll() +{ + if(m_pTempMapListHeap) + m_pTempMapListHeap->Reset(); + m_pFirstMapEntry = 0; + m_pLastMapEntry = 0; +} + +void CConsole::Con_Chain(IResult *pResult, void *pUserData) +{ + CChain *pInfo = (CChain *)pUserData; + pInfo->m_pfnChainCallback(pResult, pInfo->m_pUserData, pInfo->m_pfnCallback, pInfo->m_pCallbackUserData); +} + +void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) +{ + CCommand *pCommand = FindCommand(pName, m_FlagMask); + + if(!pCommand) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "failed to chain '%s'", pName); + Print(IConsole::OUTPUT_LEVEL_DEBUG, "console", aBuf); + return; + } + + CChain *pChainInfo = (CChain *)mem_alloc(sizeof(CChain)); + + // store info + pChainInfo->m_pfnChainCallback = pfnChainFunc; + pChainInfo->m_pUserData = pUser; + pChainInfo->m_pfnCallback = pCommand->m_pfnCallback; + pChainInfo->m_pCallbackUserData = pCommand->m_pUserData; + + // chain + pCommand->m_pfnCallback = Con_Chain; + pCommand->m_pUserData = pChainInfo; +} + +void CConsole::StoreCommands(bool Store) +{ + if(!Store) + { + for(CExecutionQueue::CQueueEntry *pEntry = m_ExecutionQueue.m_pFirst; pEntry; pEntry = pEntry->m_pNext) + pEntry->m_pCommand->m_pfnCallback(&pEntry->m_Result, pEntry->m_pCommand->m_pUserData); + m_ExecutionQueue.Reset(); + } + m_StoreCommands = Store; +} + + +const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp) +{ + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) + { + if(str_comp_nocase(pCommand->m_pName, pName) == 0) + return pCommand; + } + } + + return 0; +} + + +extern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); } diff --git a/src/engine/shared/console.h b/src/engine/shared/console.h new file mode 100644 index 000000000..7976d72ed --- /dev/null +++ b/src/engine/shared/console.h @@ -0,0 +1,217 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONSOLE_H +#define ENGINE_SHARED_CONSOLE_H + +#include +#include +#include "memheap.h" + +class CConsole : public IConsole +{ + class CCommand : public CCommandInfo + { + public: + CCommand(bool BasicAccess) : CCommandInfo(BasicAccess) {} + CCommand *m_pNext; + int m_Flags; + bool m_Temp; + FCommandCallback m_pfnCallback; + void *m_pUserData; + + virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const; + + void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); } + }; + + + class CChain + { + public: + FChainCommandCallback m_pfnChainCallback; + FCommandCallback m_pfnCallback; + void *m_pCallbackUserData; + void *m_pUserData; + }; + + int m_FlagMask; + bool m_StoreCommands; + const char *m_paStrokeStr[2]; + CCommand *m_pFirstCommand; + + class CExecFile + { + public: + const char *m_pFilename; + CExecFile *m_pPrev; + }; + + CExecFile *m_pFirstExec; + class CConfig *m_pConfig; + class IStorage *m_pStorage; + int m_AccessLevel; + + CCommand *m_pRecycleList; + CHeap m_TempCommands; + + void TraverseChain(FCommandCallback *ppfnCallback, void **ppUserData); + + static void Con_Chain(IResult *pResult, void *pUserData); + static void Con_Echo(IResult *pResult, void *pUserData); + static void Con_Exec(IResult *pResult, void *pUserData); + static void Con_EvalIf(IResult *pResult, void *pUserData); + static void ConToggle(IResult *pResult, void *pUser); + static void ConToggleStroke(IResult *pResult, void *pUser); + static void ConModCommandAccess(IResult *pResult, void *pUser); + static void ConModCommandStatus(IResult *pResult, void *pUser); + + void ExecuteFileRecurse(const char *pFilename); + void ExecuteLineStroked(int Stroke, const char *pStr); + + struct + { + int m_OutputLevel; + FPrintCallback m_pfnPrintCallback; + void *m_pPrintCallbackUserdata; + } m_aPrintCB[MAX_PRINT_CB]; + int m_NumPrintCB; + + enum + { + CONSOLE_MAX_STR_LENGTH = 1024, + MAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2 + }; + + class CResult : public IResult + { + public: + char m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1]; + char *m_pArgsStart; + + const char *m_pCommand; + const char *m_apArgs[MAX_PARTS]; + + CResult() : IResult() + { + mem_zero(m_aStringStorage, sizeof(m_aStringStorage)); + m_pArgsStart = 0; + m_pCommand = 0; + mem_zero(m_apArgs, sizeof(m_apArgs)); + } + + CResult &operator =(const CResult &Other) + { + if(this != &Other) + { + IResult::operator=(Other); + mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage)); + m_pArgsStart = m_aStringStorage+(Other.m_pArgsStart-Other.m_aStringStorage); + m_pCommand = m_aStringStorage+(Other.m_pCommand-Other.m_aStringStorage); + for(unsigned i = 0; i < Other.m_NumArgs; ++i) + m_apArgs[i] = m_aStringStorage+(Other.m_apArgs[i]-Other.m_aStringStorage); + } + return *this; + } + + void AddArgument(const char *pArg) + { + m_apArgs[m_NumArgs++] = pArg; + } + + virtual const char *GetString(unsigned Index); + virtual int GetInteger(unsigned Index); + virtual float GetFloat(unsigned Index); + }; + + int ParseStart(CResult *pResult, const char *pString, int Length); + int ParseArgs(CResult *pResult, const char *pFormat); + + /* + This function will set pFormat to the next parameter (i,s,r,v,?) it contains and + pNext to the command. + Descriptions in brackets like [file] will be skipped. + Returns true on failure. + Expects pFormat to point at a parameter. + */ + bool NextParam(char *pNext, const char *&pFormat); + + class CExecutionQueue + { + CHeap m_Queue; + + public: + struct CQueueEntry + { + CQueueEntry *m_pNext; + CCommand *m_pCommand; + CResult m_Result; + } *m_pFirst, *m_pLast; + + void AddEntry() + { + CQueueEntry *pEntry = static_cast(m_Queue.Allocate(sizeof(CQueueEntry))); + pEntry->m_pNext = 0; + if(!m_pFirst) + m_pFirst = pEntry; + if(m_pLast) + m_pLast->m_pNext = pEntry; + m_pLast = pEntry; + (void)new(&(pEntry->m_Result)) CResult; + } + void Reset() + { + m_Queue.Reset(); + m_pFirst = m_pLast = 0; + } + } m_ExecutionQueue; + + void AddCommandSorted(CCommand *pCommand); + CCommand *FindCommand(const char *pName, int FlagMask); + + struct CMapListEntryTemp { + CMapListEntryTemp *m_pPrev; + CMapListEntryTemp *m_pNext; + char m_aName[TEMPMAP_NAME_LENGTH]; + }; + + CHeap *m_pTempMapListHeap; + CMapListEntryTemp *m_pFirstMapEntry; + CMapListEntryTemp *m_pLastMapEntry; + +public: + CConsole(int FlagMask); + ~CConsole(); + + virtual void Init(); + virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int FlagMask) const; + virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp); + virtual int PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser); + virtual int PossibleMaps(const char *pStr, FPossibleCallback pfnCallback, void *pUser); + + virtual void ParseArguments(int NumArgs, const char **ppArguments); + virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp); + virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp); + virtual void DeregisterTemp(const char *pName); + virtual void DeregisterTempAll(); + virtual void RegisterTempMap(const char *pName); + virtual void DeregisterTempMap(const char *pName); + virtual void DeregisterTempMapAll(); + virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser); + virtual void StoreCommands(bool Store); + + virtual bool ArgStringIsValid(const char *pFormat); + virtual bool LineIsValid(const char *pStr); + virtual void ExecuteLine(const char *pStr); + virtual void ExecuteLineFlag(const char *pStr, int FlagMask); + virtual bool ExecuteFile(const char *pFilename); + + virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData); + virtual void SetPrintOutputLevel(int Index, int OutputLevel); + virtual void Print(int Level, const char *pFrom, const char *pStr, bool Highlighted=false); + + virtual int ParseCommandArgs(const char *pArgs, const char *pFormat, FCommandCallback pfnCallback, void *pContext); + + void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); } +}; + +#endif diff --git a/src/engine/shared/datafile.cpp b/src/engine/shared/datafile.cpp new file mode 100644 index 000000000..d0b88376f --- /dev/null +++ b/src/engine/shared/datafile.cpp @@ -0,0 +1,801 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "datafile.h" + +#include +#include +#include +#include +#include + +static const int DEBUG=0; + +struct CDatafileItemType +{ + int m_Type; + int m_Start; + int m_Num; +} ; + +struct CDatafileItem +{ + int m_TypeAndID; + int m_Size; +}; + +struct CDatafileHeader +{ + char m_aID[4]; + int m_Version; + int m_Size; + int m_Swaplen; + int m_NumItemTypes; + int m_NumItems; + int m_NumRawData; + int m_ItemSize; + int m_DataSize; +}; + +struct CDatafileData +{ + int m_NumItemTypes; + int m_NumItems; + int m_NumRawData; + int m_ItemSize; + int m_DataSize; + char m_aStart[4]; +}; + +struct CDatafileInfo +{ + CDatafileItemType *m_pItemTypes; + int *m_pItemOffsets; + int *m_pDataOffsets; + int *m_pDataSizes; + + char *m_pItemStart; + char *m_pDataStart; +}; + +struct CDatafile +{ + IOHANDLE m_File; + SHA256_DIGEST m_Sha256; + unsigned m_Crc; + CDatafileInfo m_Info; + CDatafileHeader m_Header; + int m_DataStartOffset; + char **m_ppDataPtrs; + int *m_pDataSizes; + char *m_pData; +}; + +bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int StorageType) +{ + dbg_msg("datafile", "loading. filename='%s'", pFilename); + + IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!File) + { + dbg_msg("datafile", "could not open '%s'", pFilename); + return false; + } + + + // take the hashes of the file and store them + SHA256_CTX Sha256Ctx; + sha256_init(&Sha256Ctx); + unsigned Crc = crc32(0L, 0x0, 0); + { + enum + { + BUFFER_SIZE = 64*1024 + }; + + unsigned char aBuffer[BUFFER_SIZE]; + + while(1) + { + unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE); + if(Bytes == 0) + break; + sha256_update(&Sha256Ctx, aBuffer, Bytes); + Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention + } + + io_seek(File, 0, IOSEEK_START); + } + + // TODO: change this header + CDatafileHeader Header; + io_read(File, &Header, sizeof(Header)); + if(Header.m_aID[0] != 'A' || Header.m_aID[1] != 'T' || Header.m_aID[2] != 'A' || Header.m_aID[3] != 'D') + { + if(Header.m_aID[0] != 'D' || Header.m_aID[1] != 'A' || Header.m_aID[2] != 'T' || Header.m_aID[3] != 'A') + { + dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aID[0], Header.m_aID[1], Header.m_aID[2], Header.m_aID[3]); + io_close(File); + return 0; + } + } + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); +#endif + if(Header.m_Version != 3 && Header.m_Version != 4) + { + dbg_msg("datafile", "wrong version. version=%x", Header.m_Version); + io_close(File); + return 0; + } + + // read in the rest except the data + int64 Size = 0; + Size += Header.m_NumItemTypes*sizeof(CDatafileItemType); + Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int); + if(Header.m_Version == 4) + Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell + Size += Header.m_ItemSize; + + int64 AllocSize = Size; + AllocSize += sizeof(CDatafile); // add space for info structure + AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers + AllocSize += Header.m_NumRawData*sizeof(int); // add space for data sizes + if(Size > (int64(1)<<31) || Header.m_NumItemTypes < 0 || Header.m_NumItems < 0 || Header.m_NumRawData < 0 || Header.m_ItemSize < 0) + { + io_close(File); + dbg_msg("datafile", "unable to load file, invalid file information"); + return false; + } + + CDatafile *pTmpDataFile = (CDatafile*)mem_alloc(AllocSize); + pTmpDataFile->m_Header = Header; + pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size; + pTmpDataFile->m_ppDataPtrs = (char **)(pTmpDataFile+1); + pTmpDataFile->m_pDataSizes = (int *)(pTmpDataFile->m_ppDataPtrs + Header.m_NumRawData); + pTmpDataFile->m_pData = (char *)(pTmpDataFile->m_pDataSizes + Header.m_NumRawData); + pTmpDataFile->m_File = File; + pTmpDataFile->m_Sha256 = sha256_finish(&Sha256Ctx); + pTmpDataFile->m_Crc = Crc; + + // clear the data pointers and sizes + mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*)); + mem_zero(pTmpDataFile->m_pDataSizes, Header.m_NumRawData*sizeof(int)); + + // read types, offsets, sizes and item data + unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size); + if(ReadSize != Size) + { + io_close(pTmpDataFile->m_File); + mem_free(pTmpDataFile); + pTmpDataFile = 0; + dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", unsigned(Size), ReadSize); + return false; + } + + Close(); + m_pDataFile = pTmpDataFile; + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(m_pDataFile->m_pData, sizeof(int), minimum(static_cast(Header.m_Swaplen), static_cast(Size)) / sizeof(int)); +#endif + + //if(DEBUG) + { + dbg_msg("datafile", "allocsize=%d", unsigned(AllocSize)); + dbg_msg("datafile", "readsize=%d", ReadSize); + dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen); + dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize); + } + + m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData; + m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes]; + m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems]; + m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; + + if(Header.m_Version == 4) + m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData]; + else + m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; + m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize; + + dbg_msg("datafile", "loading done. datafile='%s'", pFilename); + + if(DEBUG) + { + /* + for(int i = 0; i < m_pDataFile->data.num_raw_data; i++) + { + void *p = datafile_get_data(df, i); + dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size); + } + + for(int i = 0; i < datafile_num_items(df); i++) + { + int type, id; + void *data = datafile_get_item(df, i, &type, &id); + dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]); + int *idata = (int*)data; + for(int k = 0; k < 3; k++) + dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]); + } + + for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++) + { + dbg_msg("map", "\t%d: type=%x start=%d num=%d", i, + m_pDataFile->info.m_aItemTypes[i].type, + m_pDataFile->info.m_aItemTypes[i].start, + m_pDataFile->info.m_aItemTypes[i].num); + for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++) + { + int type, id; + datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id); + if(type != m_pDataFile->info.m_aItemTypes[i].type) + dbg_msg("map", "\tERROR"); + } + } + */ + } + + return true; +} + +int CDataFileReader::NumData() const +{ + if(!m_pDataFile) { return 0; } + return m_pDataFile->m_Header.m_NumRawData; +} + +int CDataFileReader::GetFileDataSize(int Index) const +{ + if(!m_pDataFile) { return 0; } + + if(Index == m_pDataFile->m_Header.m_NumRawData-1) + return m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index]; + return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index]; +} + +int CDataFileReader::GetDataSize(int Index) const +{ + if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData) + { + return 0; + } + + if(!m_pDataFile->m_ppDataPtrs[Index]) + { + if(m_pDataFile->m_Header.m_Version >= 4) + { + return m_pDataFile->m_Info.m_pDataSizes[Index]; + } + else + { + return GetFileDataSize(Index); + } + } + return m_pDataFile->m_pDataSizes[Index]; +} + +void *CDataFileReader::GetDataImpl(int Index, int Swap) +{ + if(!m_pDataFile) { return 0; } + + if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData) + return 0; + + // load it if needed + if(!m_pDataFile->m_ppDataPtrs[Index]) + { + // fetch the data size + int DataSize = GetFileDataSize(Index); +#if defined(CONF_ARCH_ENDIAN_BIG) + int SwapSize = DataSize; +#endif + + if(m_pDataFile->m_Header.m_Version == 4) + { + // v4 has compressed data + void *pTemp = (char *)mem_alloc(DataSize); + unsigned long UncompressedSize = m_pDataFile->m_Info.m_pDataSizes[Index]; + unsigned long s; + + dbg_msg("datafile", "loading data index=%d size=%d uncompressed=%lu", Index, DataSize, UncompressedSize); + m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(UncompressedSize); + m_pDataFile->m_pDataSizes[Index] = UncompressedSize; + + // read the compressed data + io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); + io_read(m_pDataFile->m_File, pTemp, DataSize); + + // decompress the data, TODO: check for errors + s = UncompressedSize; + uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention +#if defined(CONF_ARCH_ENDIAN_BIG) + SwapSize = s; +#endif + + // clean up the temporary buffers + mem_free(pTemp); + } + else + { + // load the data + dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize); + m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(DataSize); + m_pDataFile->m_pDataSizes[Index] = DataSize; + io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); + io_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize); + } + +#if defined(CONF_ARCH_ENDIAN_BIG) + if(Swap && SwapSize) + swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int)); +#endif + } + + return m_pDataFile->m_ppDataPtrs[Index]; +} + +void *CDataFileReader::GetData(int Index) +{ + return GetDataImpl(Index, 0); +} + +void *CDataFileReader::GetDataSwapped(int Index) +{ + return GetDataImpl(Index, 1); +} + +void CDataFileReader::ReplaceData(int Index, char *pData, int Size) +{ + if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData) + return; + + // make sure the data has been loaded + GetDataImpl(Index, 0); + + UnloadData(Index); + m_pDataFile->m_ppDataPtrs[Index] = pData; + m_pDataFile->m_pDataSizes[Index] = Size; +} + +void CDataFileReader::UnloadData(int Index) +{ + if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData) + return; + + mem_free(m_pDataFile->m_ppDataPtrs[Index]); + m_pDataFile->m_ppDataPtrs[Index] = 0x0; + m_pDataFile->m_pDataSizes[Index] = 0; +} + +int CDataFileReader::GetFileItemSize(int Index) const +{ + if(!m_pDataFile) { return 0; } + if(Index == m_pDataFile->m_Header.m_NumItems-1) + return m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index]; + return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index]; +} + +int CDataFileReader::GetItemSize(int Index) const +{ + int FileSize = GetFileItemSize(Index); + if(FileSize == 0) + { + return 0; + } + return FileSize - sizeof(CDatafileItem); +} + +void *CDataFileReader::GetItem(int Index, int *pType, int *pID) +{ + if(!m_pDataFile || Index < 0 || Index >= m_pDataFile->m_Header.m_NumItems) + { + if(pType) + *pType = 0; + if(pID) + *pID = 0; + + return 0; + } + + CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]); + if(pType) + *pType = (i->m_TypeAndID>>16)&0xffff; // remove sign extention + if(pID) + *pID = i->m_TypeAndID&0xffff; + return (void *)(i+1); +} + +void CDataFileReader::GetType(int Type, int *pStart, int *pNum) +{ + *pStart = 0; + *pNum = 0; + + if(!m_pDataFile) + return; + + for(int i = 0; i < m_pDataFile->m_Header.m_NumItemTypes; i++) + { + if(m_pDataFile->m_Info.m_pItemTypes[i].m_Type == Type) + { + *pStart = m_pDataFile->m_Info.m_pItemTypes[i].m_Start; + *pNum = m_pDataFile->m_Info.m_pItemTypes[i].m_Num; + return; + } + } +} + +void *CDataFileReader::FindItem(int Type, int ID) +{ + if(!m_pDataFile) return 0; + + int Start, Num; + GetType(Type, &Start, &Num); + for(int i = 0; i < Num; i++) + { + int ItemID; + void *pItem = GetItem(Start+i,0, &ItemID); + if(ID == ItemID) + return pItem; + } + return 0; +} + +int CDataFileReader::NumItems() const +{ + if(!m_pDataFile) return 0; + return m_pDataFile->m_Header.m_NumItems; +} + +bool CDataFileReader::Close() +{ + if(!m_pDataFile) + return true; + + // free the data that is loaded + int i; + for(i = 0; i < m_pDataFile->m_Header.m_NumRawData; i++) + { + mem_free(m_pDataFile->m_ppDataPtrs[i]); + m_pDataFile->m_pDataSizes[i] = 0; + } + + io_close(m_pDataFile->m_File); + mem_free(m_pDataFile); + m_pDataFile = 0; + return true; +} + +SHA256_DIGEST CDataFileReader::Sha256() const +{ + if(!m_pDataFile) return SHA256_ZEROED; + return m_pDataFile->m_Sha256; +} + +unsigned CDataFileReader::Crc() const +{ + if(!m_pDataFile) return 0xFFFFFFFF; + return m_pDataFile->m_Crc; +} + +bool CDataFileReader::CheckSha256(IOHANDLE Handle, const void *pSha256) +{ + // read the hash of the file + SHA256_CTX Sha256Ctx; + sha256_init(&Sha256Ctx); + unsigned char aBuffer[64*1024]; + + while(1) + { + unsigned Bytes = io_read(Handle, aBuffer, sizeof(aBuffer)); + if(Bytes == 0) + break; + sha256_update(&Sha256Ctx, aBuffer, Bytes); + } + + io_seek(Handle, 0, IOSEEK_START); + SHA256_DIGEST Sha256 = sha256_finish(&Sha256Ctx); + + return !sha256_comp(*(const SHA256_DIGEST *)pSha256, Sha256); +} + + +CDataFileWriter::CDataFileWriter() +{ + m_File = 0; + m_pItemTypes = static_cast(mem_alloc(sizeof(CItemTypeInfo) * MAX_ITEM_TYPES)); + m_pItems = static_cast(mem_alloc(sizeof(CItemInfo) * MAX_ITEMS)); + m_pDatas = static_cast(mem_alloc(sizeof(CDataInfo) * MAX_DATAS)); +} + +CDataFileWriter::~CDataFileWriter() +{ + mem_free(m_pItemTypes); + m_pItemTypes = 0; + mem_free(m_pItems); + m_pItems = 0; + mem_free(m_pDatas); + m_pDatas = 0; +} + +bool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename) +{ + dbg_assert(!m_File, "a file already exists"); + m_File = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!m_File) + return false; + + m_NumItems = 0; + m_NumDatas = 0; + m_NumItemTypes = 0; + mem_zero(m_pItemTypes, sizeof(CItemTypeInfo) * MAX_ITEM_TYPES); + + for(int i = 0; i < MAX_ITEM_TYPES; i++) + { + m_pItemTypes[i].m_First = -1; + m_pItemTypes[i].m_Last = -1; + } + + return true; +} + +int CDataFileWriter::AddItem(int Type, int ID, int Size, const void *pData) +{ + if(!m_File) return 0; + + dbg_assert(Type >= 0 && Type < 0xFFFF, "incorrect type"); + dbg_assert(m_NumItems < 1024, "too many items"); + dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + + m_pItems[m_NumItems].m_Type = Type; + m_pItems[m_NumItems].m_ID = ID; + m_pItems[m_NumItems].m_Size = Size; + + // copy data + m_pItems[m_NumItems].m_pData = mem_alloc(Size); + mem_copy(m_pItems[m_NumItems].m_pData, pData, Size); + + if(!m_pItemTypes[Type].m_Num) // count item types + m_NumItemTypes++; + + // link + m_pItems[m_NumItems].m_Prev = m_pItemTypes[Type].m_Last; + m_pItems[m_NumItems].m_Next = -1; + + if(m_pItemTypes[Type].m_Last != -1) + m_pItems[m_pItemTypes[Type].m_Last].m_Next = m_NumItems; + m_pItemTypes[Type].m_Last = m_NumItems; + + if(m_pItemTypes[Type].m_First == -1) + m_pItemTypes[Type].m_First = m_NumItems; + + m_pItemTypes[Type].m_Num++; + + m_NumItems++; + return m_NumItems-1; +} + +int CDataFileWriter::AddData(int Size, const void *pData) +{ + if(!m_File) return 0; + + dbg_assert(m_NumDatas < 1024, "too much data"); + + CDataInfo *pInfo = &m_pDatas[m_NumDatas]; + unsigned long s = compressBound(Size); + void *pCompData = mem_alloc(s); // temporary buffer that we use during compression + + int Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention + if(Result != Z_OK) + { + dbg_msg("datafile", "compression error %d", Result); + dbg_assert(0, "zlib error"); + } + + pInfo->m_UncompressedSize = Size; + pInfo->m_CompressedSize = (int)s; + pInfo->m_pCompressedData = mem_alloc(pInfo->m_CompressedSize); + mem_copy(pInfo->m_pCompressedData, pCompData, pInfo->m_CompressedSize); + mem_free(pCompData); + + m_NumDatas++; + return m_NumDatas-1; +} + +int CDataFileWriter::AddDataSwapped(int Size, const void *pData) +{ + dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + +#if defined(CONF_ARCH_ENDIAN_BIG) + void *pSwapped = mem_alloc(Size); // temporary buffer that we use during compression + mem_copy(pSwapped, pData, Size); + swap_endian(pSwapped, sizeof(int), Size/sizeof(int)); + int Index = AddData(Size, pSwapped); + mem_free(pSwapped); + return Index; +#else + return AddData(Size, pData); +#endif +} + + +int CDataFileWriter::Finish() +{ + if(!m_File) return 0; + + int ItemSize = 0; + int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize; + int DataSize = 0; + CDatafileHeader Header; + + // we should now write this file! + if(DEBUG) + dbg_msg("datafile", "writing"); + + // calculate sizes + for(int i = 0; i < m_NumItems; i++) + { + if(DEBUG) + dbg_msg("datafile", "item=%d size=%d (%d)", i, m_pItems[i].m_Size, (int)(m_pItems[i].m_Size+sizeof(CDatafileItem))); + ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem); + } + + + for(int i = 0; i < m_NumDatas; i++) + DataSize += m_pDatas[i].m_CompressedSize; + + // calculate the complete size + TypesSize = m_NumItemTypes*sizeof(CDatafileItemType); + HeaderSize = sizeof(CDatafileHeader); + OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes + FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize; + SwapSize = FileSize - DataSize; + + (void)SwapSize; + + if(DEBUG) + dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize); + + // construct Header + { + Header.m_aID[0] = 'D'; + Header.m_aID[1] = 'A'; + Header.m_aID[2] = 'T'; + Header.m_aID[3] = 'A'; + Header.m_Version = 4; + Header.m_Size = FileSize - 16; + Header.m_Swaplen = SwapSize - 16; + Header.m_NumItemTypes = m_NumItemTypes; + Header.m_NumItems = m_NumItems; + Header.m_NumRawData = m_NumDatas; + Header.m_ItemSize = ItemSize; + Header.m_DataSize = DataSize; + + // write Header + if(DEBUG) + dbg_msg("datafile", "HeaderSize=%d", (int)sizeof(Header)); +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); +#endif + io_write(m_File, &Header, sizeof(Header)); + } + + // write types + for(int i = 0, Count = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write info + CDatafileItemType Info; + Info.m_Type = i; + Info.m_Start = Count; + Info.m_Num = m_pItemTypes[i].m_Num; + if(DEBUG) + dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num); +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int)); +#endif + io_write(m_File, &Info, sizeof(Info)); + Count += m_pItemTypes[i].m_Num; + } + } + + // write item offsets + for(int i = 0, Offset = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write all m_pItems in of this type + int k = m_pItemTypes[i].m_First; + while(k != -1) + { + if(DEBUG) + dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset); + int Temp = Offset; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); +#endif + io_write(m_File, &Temp, sizeof(Temp)); + Offset += m_pItems[k].m_Size + sizeof(CDatafileItem); + + // next + k = m_pItems[k].m_Next; + } + } + } + + // write data offsets + for(int i = 0, Offset = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset); + int Temp = Offset; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); +#endif + io_write(m_File, &Temp, sizeof(Temp)); + Offset += m_pDatas[i].m_CompressedSize; + } + + // write data uncompressed sizes + for(int i = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize); + int UncompressedSize = m_pDatas[i].m_UncompressedSize; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int)); +#endif + io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); + } + + // write m_pItems + for(int i = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write all m_pItems in of this type + int k = m_pItemTypes[i].m_First; + while(k != -1) + { + CDatafileItem Item; + Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID; + Item.m_Size = m_pItems[k].m_Size; + if(DEBUG) + dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size); + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); + swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int)); +#endif + io_write(m_File, &Item, sizeof(Item)); + io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size); + + // next + k = m_pItems[k].m_Next; + } + } + } + + // write data + for(int i = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data id=%d size=%d", i, m_pDatas[i].m_CompressedSize); + io_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize); + } + + // free data + for(int i = 0; i < m_NumItems; i++) + mem_free(m_pItems[i].m_pData); + for(int i = 0; i < m_NumDatas; ++i) + mem_free(m_pDatas[i].m_pCompressedData); + + io_close(m_File); + m_File = 0; + + if(DEBUG) + dbg_msg("datafile", "done"); + return 1; +} diff --git a/src/engine/shared/datafile.h b/src/engine/shared/datafile.h new file mode 100644 index 000000000..98529e5f8 --- /dev/null +++ b/src/engine/shared/datafile.h @@ -0,0 +1,97 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_DATAFILE_H +#define ENGINE_SHARED_DATAFILE_H + +#include +#include + +// raw datafile access +class CDataFileReader +{ + struct CDatafile *m_pDataFile; + void *GetDataImpl(int Index, int Swap); + int GetFileDataSize(int Index) const; + int GetFileItemSize(int Index) const; +public: + CDataFileReader() : m_pDataFile(0) {} + ~CDataFileReader() { Close(); } + + bool IsOpen() const { return m_pDataFile != 0; } + + bool Open(class IStorage *pStorage, const char *pFilename, int StorageType); + bool Close(); + + void *GetData(int Index); + void *GetDataSwapped(int Index); // makes sure that the data is 32bit LE ints when saved + int GetDataSize(int Index) const; + void ReplaceData(int Index, char *pData, int Size); + void UnloadData(int Index); + void *GetItem(int Index, int *pType, int *pID); + int GetItemSize(int Index) const; + void GetType(int Type, int *pStart, int *pNum); + void *FindItem(int Type, int ID); + int NumItems() const; + int NumData() const; + void Unload(); + + SHA256_DIGEST Sha256() const; + unsigned Crc() const; + + static bool CheckSha256(IOHANDLE Handle, const void *pSha256); +}; + +// write access +class CDataFileWriter +{ + struct CDataInfo + { + int m_UncompressedSize; + int m_CompressedSize; + void *m_pCompressedData; + }; + + struct CItemInfo + { + int m_Type; + int m_ID; + int m_Size; + int m_Next; + int m_Prev; + void *m_pData; + }; + + struct CItemTypeInfo + { + int m_Num; + int m_First; + int m_Last; + }; + + enum + { + MAX_ITEM_TYPES=0xffff, + MAX_ITEMS=1024, + MAX_DATAS=1024, + }; + + IOHANDLE m_File; + int m_NumItems; + int m_NumDatas; + int m_NumItemTypes; + CItemTypeInfo *m_pItemTypes; + CItemInfo *m_pItems; + CDataInfo *m_pDatas; + +public: + CDataFileWriter(); + ~CDataFileWriter(); + bool Open(class IStorage *pStorage, const char *Filename); + int AddData(int Size, const void *pData); + int AddDataSwapped(int Size, const void *pData); + int AddItem(int Type, int ID, int Size, const void *pData); + int Finish(); +}; + + +#endif diff --git a/src/engine/shared/demo.cpp b/src/engine/shared/demo.cpp new file mode 100644 index 000000000..4df8d08b3 --- /dev/null +++ b/src/engine/shared/demo.cpp @@ -0,0 +1,875 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include +#include + +#include "compression.h" +#include "datafile.h" +#include "demo.h" +#include "memheap.h" +#include "network.h" +#include "snapshot.h" + +static const unsigned char gs_aHeaderMarker[7] = {'T', 'W', 'D', 'E', 'M', 'O', 0}; +static const unsigned char gs_ActVersion = 4; +static const int gs_LengthOffset = 152; +static const int gs_NumMarkersOffset = 176; + +CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta) +{ + m_File = 0; + m_LastTickMarker = -1; + m_pSnapshotDelta = pSnapshotDelta; + m_Huffman.Init(); +} + +void CDemoRecorder::Init(class IConsole *pConsole, class IStorage *pStorage) +{ + m_pConsole = pConsole; + m_pStorage = pStorage; +} + +// Record +int CDemoRecorder::Start(const char *pFilename, const char *pNetVersion, const char *pMap, SHA256_DIGEST Sha256, unsigned Crc, const char *pType) +{ + CDemoHeader Header; + if(m_File) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Demo recording is already active"); + return -1; + } + + // open mapfile + char aMapFilename[128]; + // try the normal maps folder + str_format(aMapFilename, sizeof(aMapFilename), "maps/%s.map", pMap); + IOHANDLE MapFile = m_pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL, 0, 0, CDataFileReader::CheckSha256, &Sha256); + if(!MapFile) + { + // try the downloaded maps (sha256) + char aSha256[SHA256_MAXSTRSIZE]; + sha256_str(Sha256, aSha256, sizeof(aSha256)); + str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%s.map", pMap, aSha256); + MapFile = m_pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL, 0, 0, CDataFileReader::CheckSha256, &Sha256); + } + if(!MapFile) + { + // try the downloaded maps (crc) + str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", pMap, Crc); + MapFile = m_pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL, 0, 0, CDataFileReader::CheckSha256, &Sha256); + } + if(!MapFile) + { + // search for the map within subfolders + char aBuf[IO_MAX_PATH_LENGTH]; + str_format(aMapFilename, sizeof(aMapFilename), "%s.map", pMap); + if(m_pStorage->FindFile(aMapFilename, "maps", IStorage::TYPE_ALL, aBuf, sizeof(aBuf))) + MapFile = m_pStorage->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL, 0, 0, CDataFileReader::CheckSha256, &Sha256); + } + if(!MapFile) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Unable to open mapfile '%s'", pMap); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); + return -1; + } + + IOHANDLE DemoFile = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!DemoFile) + { + io_close(MapFile); + MapFile = 0; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Unable to open '%s' for recording", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); + return -1; + } + + // write header + mem_zero(&Header, sizeof(Header)); + mem_copy(Header.m_aMarker, gs_aHeaderMarker, sizeof(Header.m_aMarker)); + Header.m_Version = gs_ActVersion; + str_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion)); + str_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName)); + unsigned MapSize = io_length(MapFile); + uint_to_bytes_be(Header.m_aMapSize, MapSize); + uint_to_bytes_be(Header.m_aMapCrc, Crc); + str_copy(Header.m_aType, pType, sizeof(Header.m_aType)); + // Header.m_Length - add this on stop + str_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp)); + // Header.m_aNumTimelineMarkers - add this on stop + // Header.m_aTimelineMarkers - add this on stop + io_write(DemoFile, &Header, sizeof(Header)); + + // write map data + unsigned char aChunk[1024*64]; + while(1) + { + int Bytes = io_read(MapFile, &aChunk, sizeof(aChunk)); + if(Bytes <= 0) + break; + io_write(DemoFile, &aChunk, Bytes); + } + io_close(MapFile); + + m_LastKeyFrame = -1; + m_LastTickMarker = -1; + m_FirstTick = -1; + m_NumTimelineMarkers = 0; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Recording to '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); + m_File = DemoFile; + + return 0; +} + +/* + Tickmarker + 7 = Always set + 6 = Keyframe flag + 0-5 = Delta tick + + Normal + 7 = Not set + 5-6 = Type + 0-4 = Size +*/ + +enum +{ + CHUNKTYPEFLAG_TICKMARKER = 0x80, + CHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set + + CHUNKMASK_TICK = 0x3f, + CHUNKMASK_TYPE = 0x60, + CHUNKMASK_SIZE = 0x1f, + + CHUNKTYPE_SNAPSHOT = 1, + CHUNKTYPE_MESSAGE = 2, + CHUNKTYPE_DELTA = 3, + + CHUNKFLAG_BIGSIZE = 0x10 +}; + +void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) +{ + if(m_LastTickMarker == -1 || Tick-m_LastTickMarker > 63 || Keyframe) + { + unsigned char aChunk[5]; + aChunk[0] = CHUNKTYPEFLAG_TICKMARKER; + int_to_bytes_be(aChunk+1, Tick); + + if(Keyframe) + aChunk[0] |= CHUNKTICKFLAG_KEYFRAME; + + io_write(m_File, aChunk, sizeof(aChunk)); + } + else + { + unsigned char aChunk[1]; + aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | (Tick-m_LastTickMarker); + io_write(m_File, aChunk, sizeof(aChunk)); + } + + m_LastTickMarker = Tick; + if(m_FirstTick < 0) + m_FirstTick = Tick; +} + +void CDemoRecorder::Write(int Type, const void *pData, int Size) +{ + if(!m_File) + return; + + char aBuffer[64*1024]; + char aBuffer2[64*1024]; + + /* pad the data with 0 so we get an alignment of 4, + else the compression won't work and miss some bytes */ + mem_copy(aBuffer2, pData, Size); + while(Size&3) + aBuffer2[Size++] = 0; + Size = CVariableInt::Compress(aBuffer2, Size, aBuffer, sizeof(aBuffer)); // buffer2 -> buffer + if(Size < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_recorder", "error during intpack compression"); + return; + } + Size = m_Huffman.Compress(aBuffer, Size, aBuffer2, sizeof(aBuffer2)); // buffer -> buffer2 + if(Size < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_recorder", "error during network compression"); + return; + } + + unsigned char aChunk[3]; + aChunk[0] = ((Type&0x3)<<5); + if(Size < 30) + { + aChunk[0] |= Size; + io_write(m_File, aChunk, 1); + } + else + { + if(Size < 256) + { + aChunk[0] |= 30; + aChunk[1] = Size&0xff; + io_write(m_File, aChunk, 2); + } + else + { + aChunk[0] |= 31; + aChunk[1] = Size&0xff; + aChunk[2] = Size>>8; + io_write(m_File, aChunk, 3); + } + } + + io_write(m_File, aBuffer2, Size); +} + +void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) +{ + char aTmpData[CSnapshot::MAX_SIZE]; + + if(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5) + { + // write full tickmarker + WriteTickMarker(Tick, 1); + + // write snapshot + int SnapSize = ((CSnapshot*)pData)->Serialize(aTmpData); + Write(CHUNKTYPE_SNAPSHOT, aTmpData, SnapSize); + + m_LastKeyFrame = Tick; + mem_copy(m_aLastSnapshotData, pData, Size); + } + else + { + // write tickmarker + WriteTickMarker(Tick, 0); + + // create delta + int DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aTmpData); + if(DeltaSize) + { + // record delta + Write(CHUNKTYPE_DELTA, aTmpData, DeltaSize); + mem_copy(m_aLastSnapshotData, pData, Size); + } + } +} + +void CDemoRecorder::RecordMessage(const void *pData, int Size) +{ + Write(CHUNKTYPE_MESSAGE, pData, Size); +} + +int CDemoRecorder::Stop() +{ + if(!m_File) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "No active demo recording to stop"); + return -1; + } + + // add the demo length to the header + io_seek(m_File, gs_LengthOffset, IOSEEK_START); + unsigned char aLength[4]; + int_to_bytes_be(aLength, Length()); + io_write(m_File, aLength, sizeof(aLength)); + + // add the timeline markers to the header + io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START); + unsigned char aNumMarkers[4]; + int_to_bytes_be(aNumMarkers, m_NumTimelineMarkers); + io_write(m_File, aNumMarkers, sizeof(aNumMarkers)); + for(int i = 0; i < m_NumTimelineMarkers; i++) + { + unsigned char aMarker[4]; + int_to_bytes_be(aMarker, m_aTimelineMarkers[i]); + io_write(m_File, aMarker, sizeof(aMarker)); + } + + io_close(m_File); + m_File = 0; + m_LastKeyFrame = -1; + m_LastTickMarker = -1; + m_FirstTick = -1; + m_NumTimelineMarkers = 0; + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Stopped recording"); + + return 0; +} + +void CDemoRecorder::AddDemoMarker() +{ + if(m_LastTickMarker < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Cannot add timeline marker: demo recording not active"); + return; + } + else if(m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Cannot add timeline marker: too many markers in the demo file"); + return; + } + + // not more than 1 marker in a second + if(m_NumTimelineMarkers > 0) + { + int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1]; + if(Diff < SERVER_TICK_SPEED*1.0f) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Cannot add timeline marker: marker is too close to previous marker"); + return; + } + } + + m_aTimelineMarkers[m_NumTimelineMarkers++] = m_LastTickMarker; + + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker"); +} + + + +CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta) +{ + m_Huffman.Init(); + m_File = 0; + m_aErrorMsg[0] = 0; + m_pKeyFrames = 0; + + m_pSnapshotDelta = pSnapshotDelta; + m_LastSnapshotDataSize = -1; +} + +void CDemoPlayer::Init(class IConsole *pConsole, class IStorage *pStorage) +{ + m_pConsole = pConsole; + m_pStorage = pStorage; +} + +void CDemoPlayer::SetListener(IListener *pListener) +{ + m_pListener = pListener; +} + + +int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) +{ + unsigned char Chunk = 0; + + *pSize = 0; + *pType = 0; + + if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk)) + return -1; + + if(Chunk&CHUNKTYPEFLAG_TICKMARKER) + { + // decode tick marker + int Tickdelta = Chunk&(CHUNKMASK_TICK); + *pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME); + + if(Tickdelta == 0) + { + unsigned char aTickData[4]; + if(io_read(m_File, aTickData, sizeof(aTickData)) != sizeof(aTickData)) + return -1; + *pTick = bytes_be_to_int(aTickData); + } + else + { + *pTick += Tickdelta; + } + } + else + { + // decode normal chunk + *pType = (Chunk&CHUNKMASK_TYPE)>>5; + *pSize = Chunk&CHUNKMASK_SIZE; + + if(*pSize == 30) + { + unsigned char aSizeData[1]; + if(io_read(m_File, aSizeData, sizeof(aSizeData)) != sizeof(aSizeData)) + return -1; + *pSize = aSizeData[0]; + } + else if(*pSize == 31) + { + unsigned char aSizeData[2]; + if(io_read(m_File, aSizeData, sizeof(aSizeData)) != sizeof(aSizeData)) + return -1; + *pSize = (aSizeData[1]<<8) | aSizeData[0]; + } + } + + return 0; +} + +void CDemoPlayer::ScanFile() +{ + CHeap Heap; + CKeyFrameSearch *pFirstKey = 0; + CKeyFrameSearch *pCurrentKey = 0; + int ChunkTick = 0; + + long StartPos = io_tell(m_File); + m_Info.m_SeekablePoints = 0; + + while(1) + { + long CurrentPos = io_tell(m_File); + + int ChunkSize, ChunkType; + if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) + break; + + // read the chunk + if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) + { + if(ChunkType&CHUNKTICKFLAG_KEYFRAME) + { + // save the position + CKeyFrameSearch *pKey = (CKeyFrameSearch *)Heap.Allocate(sizeof(CKeyFrameSearch)); + pKey->m_Frame.m_Filepos = CurrentPos; + pKey->m_Frame.m_Tick = ChunkTick; + pKey->m_pNext = 0; + if(pCurrentKey) + pCurrentKey->m_pNext = pKey; + if(!pFirstKey) + pFirstKey = pKey; + pCurrentKey = pKey; + m_Info.m_SeekablePoints++; + } + + if(m_Info.m_Info.m_FirstTick == -1) + m_Info.m_Info.m_FirstTick = ChunkTick; + m_Info.m_Info.m_LastTick = ChunkTick; + } + else if(ChunkSize) + io_skip(m_File, ChunkSize); + } + + // copy all the frames to an array instead for fast access + int i; + m_pKeyFrames = (CKeyFrame*)mem_alloc(m_Info.m_SeekablePoints*sizeof(CKeyFrame)); + for(pCurrentKey = pFirstKey, i = 0; pCurrentKey; pCurrentKey = pCurrentKey->m_pNext, i++) + m_pKeyFrames[i] = pCurrentKey->m_Frame; + + // destroy the temporary heap and seek back to the start + io_seek(m_File, StartPos, IOSEEK_START); +} + +void CDemoPlayer::DoTick() +{ + static char aCompressedData[CSnapshot::MAX_SIZE]; + static char aDecompressed[CSnapshot::MAX_SIZE]; + static char aData[CSnapshot::MAX_SIZE]; + static char aNewSnap[CSnapshot::MAX_SIZE]; + bool GotSnapshot = false; + + // update ticks + m_Info.m_PreviousTick = m_Info.m_Info.m_CurrentTick; + m_Info.m_Info.m_CurrentTick = m_Info.m_NextTick; + int ChunkTick = m_Info.m_Info.m_CurrentTick; + + while(1) + { + int DataSize = 0; + int ChunkType, ChunkSize; + if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "end of file"); + if(m_Info.m_PreviousTick == -1) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "empty demo"); + Stop(); + } + else + Pause(); + break; + } + + // read the chunk + if(ChunkSize) + { + if(io_read(m_File, aCompressedData, ChunkSize) != (unsigned)ChunkSize) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error reading chunk"); + Stop(); + break; + } + + DataSize = m_Huffman.Decompress(aCompressedData, ChunkSize, aDecompressed, sizeof(aDecompressed)); + if(DataSize < 0) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during network decompression"); + Stop(); + break; + } + + DataSize = CVariableInt::Decompress(aDecompressed, DataSize, aData, sizeof(aData)); + if(DataSize < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during intpack decompression"); + Stop(); + break; + } + } + + if(ChunkType == CHUNKTYPE_DELTA) + { + // process delta snapshot + GotSnapshot = true; + + // only unpack the delta if we have a valid snapshot + if(m_LastSnapshotDataSize == -1) + continue; + + DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewSnap, aData, DataSize); + if(DataSize >= 0) + { + if(m_pListener) + m_pListener->OnDemoPlayerSnapshot(aNewSnap, DataSize); + + m_LastSnapshotDataSize = DataSize; + mem_copy(m_aLastSnapshotData, aNewSnap, DataSize); + } + else + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "error during unpacking of delta, err=%d", DataSize); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); + } + } + else if(ChunkType == CHUNKTYPE_SNAPSHOT) + { + // process full snapshot + CSnapshotBuilder Builder; + GotSnapshot = true; + + if(Builder.UnserializeSnap(aData, DataSize)) + DataSize = Builder.Finish(aNewSnap); + else + DataSize = -1; + + if(DataSize >= 0) + { + m_LastSnapshotDataSize = DataSize; + mem_copy(m_aLastSnapshotData, aNewSnap, DataSize); + if(m_pListener) + m_pListener->OnDemoPlayerSnapshot(aNewSnap, DataSize); + } + else + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "error during unpacking of snapshot, err=%d", DataSize); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); + } + } + else + { + // if there were no snapshots in this tick, replay the last one + if(!GotSnapshot && m_pListener && m_LastSnapshotDataSize != -1) + { + GotSnapshot = true; + m_pListener->OnDemoPlayerSnapshot(m_aLastSnapshotData, m_LastSnapshotDataSize); + } + + // check the remaining types + if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) + { + m_Info.m_NextTick = ChunkTick; + break; + } + else if(ChunkType == CHUNKTYPE_MESSAGE && m_pListener && m_LastSnapshotDataSize != -1) + { + m_pListener->OnDemoPlayerMessage(aData, DataSize); + } + } + } +} + +void CDemoPlayer::Pause() +{ + m_Info.m_Info.m_Paused = true; +} + +void CDemoPlayer::Unpause() +{ + m_Info.m_Info.m_Paused = false; +} + +const char *CDemoPlayer::Load(const char *pFilename, int StorageType, const char *pNetversion) +{ + m_aErrorMsg[0] = 0; + m_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!m_File) + { + str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "could not open '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); + return m_aErrorMsg; + } + + // store the filename + str_copy(m_aFilename, pFilename, sizeof(m_aFilename)); + + // clear the playback info + mem_zero(&m_Info, sizeof(m_Info)); + m_Info.m_Info.m_FirstTick = -1; + m_Info.m_Info.m_LastTick = -1; + m_Info.m_NextTick = -1; + m_Info.m_Info.m_CurrentTick = -1; + m_Info.m_PreviousTick = -1; + m_Info.m_Info.m_Speed = 1; + + m_LastSnapshotDataSize = -1; + + // read the header + io_read(m_File, &m_Info.m_Header, sizeof(m_Info.m_Header)); + if(mem_comp(m_Info.m_Header.m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) != 0) + { + str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "'%s' is not a demo file", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); + io_close(m_File); + m_File = 0; + return m_aErrorMsg; + } + + if(m_Info.m_Header.m_Version != gs_ActVersion) + { + str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "demo version %d is not supported", m_Info.m_Header.m_Version); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); + io_close(m_File); + m_File = 0; + return m_aErrorMsg; + } + + if(str_comp(m_Info.m_Header.m_aNetversion, pNetversion) != 0) + { + str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "net version '%s' is not supported", m_Info.m_Header.m_aNetversion); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); + io_close(m_File); + m_File = 0; + return m_aErrorMsg; + } + + // get demo type + if(!str_comp(m_Info.m_Header.m_aType, "client")) + m_DemoType = DEMOTYPE_CLIENT; + else if(!str_comp(m_Info.m_Header.m_aType, "server")) + m_DemoType = DEMOTYPE_SERVER; + else + m_DemoType = DEMOTYPE_INVALID; + + // read map + unsigned MapSize = bytes_be_to_uint(m_Info.m_Header.m_aMapSize); + + // check if we already have the map + // TODO: improve map checking (maps folder, check crc) + unsigned Crc = bytes_be_to_uint(m_Info.m_Header.m_aMapCrc); + char aMapFilename[128]; + str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", m_Info.m_Header.m_aMapName, Crc); + IOHANDLE MapFile = m_pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); + + if(MapFile) + { + io_skip(m_File, MapSize); + io_close(MapFile); + } + else if(MapSize > 0) + { + // get map data + unsigned char *pMapData = (unsigned char *)mem_alloc(MapSize); + io_read(m_File, pMapData, MapSize); + + // save map + MapFile = m_pStorage->OpenFile(aMapFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + io_write(MapFile, pMapData, MapSize); + io_close(MapFile); + + // free data + mem_free(pMapData); + } + + // get timeline markers + m_Info.m_Info.m_NumTimelineMarkers = minimum(bytes_be_to_int(m_Info.m_Header.m_aNumTimelineMarkers), int(MAX_TIMELINE_MARKERS)); + for(int i = 0; i < m_Info.m_Info.m_NumTimelineMarkers; i++) + m_Info.m_Info.m_aTimelineMarkers[i] = bytes_be_to_int(m_Info.m_Header.m_aTimelineMarkers[i]); + + // scan the file for interesting points + ScanFile(); + + // ready for playback + return 0; +} + +int CDemoPlayer::Play() +{ + // fill in previous and next tick + while(m_Info.m_PreviousTick == -1 && IsPlaying()) + DoTick(); + + // set start info + m_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED; + m_Info.m_LastUpdate = time_get(); + return 0; +} + +int CDemoPlayer::SetPos(float Percent) +{ + if(!m_File) + return -1; + return SetPos(m_Info.m_Info.m_FirstTick + (int)((m_Info.m_Info.m_LastTick-m_Info.m_Info.m_FirstTick)*Percent)); +} + +int CDemoPlayer::SetPos(int WantedTick) +{ + if(!m_File) + return -1; + + WantedTick = clamp(WantedTick, m_Info.m_Info.m_FirstTick, m_Info.m_Info.m_LastTick); + int KeyframeWantedTick = WantedTick - 5; // -5 because we have to have a current tick and previous tick when we do the playback + const float Percent = (KeyframeWantedTick - m_Info.m_Info.m_FirstTick) / float(m_Info.m_Info.m_LastTick - m_Info.m_Info.m_FirstTick); + + // get correct key frame + int Keyframe = clamp((int)(m_Info.m_SeekablePoints*Percent), 0, m_Info.m_SeekablePoints-1); + while(Keyframe < m_Info.m_SeekablePoints-1 && m_pKeyFrames[Keyframe].m_Tick < KeyframeWantedTick) + Keyframe++; + while(Keyframe > 0 && m_pKeyFrames[Keyframe].m_Tick > KeyframeWantedTick) + Keyframe--; + + // seek to the correct keyframe + io_seek(m_File, m_pKeyFrames[Keyframe].m_Filepos, IOSEEK_START); + + m_Info.m_NextTick = -1; + m_Info.m_Info.m_CurrentTick = -1; + m_Info.m_PreviousTick = -1; + + // playback everything until we hit our tick + while(m_Info.m_NextTick < WantedTick) + DoTick(); + + Play(); + + return 0; +} + +void CDemoPlayer::SetSpeed(float Speed) +{ + m_Info.m_Info.m_Speed = Speed; +} + +int CDemoPlayer::Update() +{ + int64 Now = time_get(); + int64 Deltatime = Now-m_Info.m_LastUpdate; + m_Info.m_LastUpdate = Now; + + if(!IsPlaying() || m_Info.m_Info.m_Paused) + return 0; + + int64 Freq = time_freq(); + m_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed); + + while(1) + { + int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; + + // break if we are ready + if(CurtickStart > m_Info.m_CurrentTime) + break; + + // do one more tick + DoTick(); + + if(m_Info.m_Info.m_Paused) + return 0; + } + + // update intratick + { + int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; + int64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED; + m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + m_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq; + } + + if(m_Info.m_Info.m_CurrentTick == m_Info.m_PreviousTick || + m_Info.m_Info.m_CurrentTick == m_Info.m_NextTick) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "tick error prev=%d cur=%d next=%d", + m_Info.m_PreviousTick, m_Info.m_Info.m_CurrentTick, m_Info.m_NextTick); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); + } + + return 0; +} + +int CDemoPlayer::Stop() +{ + if(!m_File) + return -1; + + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "Stopped playback"); + io_close(m_File); + m_File = 0; + mem_free(m_pKeyFrames); + m_pKeyFrames = 0; + m_aFilename[0] = '\0'; + return 0; +} + +void CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const +{ + const char *pFileName = m_aFilename; + const char *pExtractedName = pFileName; + const char *pEnd = 0; + for(; *pFileName; ++pFileName) + { + if(*pFileName == '/' || *pFileName == '\\') + pExtractedName = pFileName+1; + else if(*pFileName == '.') + pEnd = pFileName; + } + + int Length = pEnd > pExtractedName ? minimum(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; + str_copy(pBuffer, pExtractedName, Length); +} + +bool CDemoPlayer::GetDemoInfo(const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const +{ + if(!pDemoHeader) + return false; + + mem_zero(pDemoHeader, sizeof(CDemoHeader)); + + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!File) + return false; + + io_read(File, pDemoHeader, sizeof(CDemoHeader)); + bool Valid = mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) == 0 && pDemoHeader->m_Version == gs_ActVersion; + io_close(File); + return Valid; +} + +int CDemoPlayer::GetDemoType() const +{ + if(m_File) + return m_DemoType; + return DEMOTYPE_INVALID; +} diff --git a/src/engine/shared/demo.h b/src/engine/shared/demo.h new file mode 100644 index 000000000..e4247be7c --- /dev/null +++ b/src/engine/shared/demo.h @@ -0,0 +1,133 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_DEMO_H +#define ENGINE_SHARED_DEMO_H + +#include +#include + +#include "huffman.h" +#include "snapshot.h" + +class CDemoRecorder : public IDemoRecorder +{ + class IConsole *m_pConsole; + class IStorage *m_pStorage; + CHuffman m_Huffman; + IOHANDLE m_File; + int m_LastTickMarker; + int m_LastKeyFrame; + int m_FirstTick; + unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; + class CSnapshotDelta *m_pSnapshotDelta; + int m_NumTimelineMarkers; + int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; + + void WriteTickMarker(int Tick, int Keyframe); + void Write(int Type, const void *pData, int Size); +public: + CDemoRecorder(class CSnapshotDelta *pSnapshotDelta); + void Init(class IConsole *pConsole, class IStorage *pStorage); + + int Start(const char *pFilename, const char *pNetversion, const char *pMap, SHA256_DIGEST MapSha256, unsigned MapCrc, const char *pType); + int Stop(); + void AddDemoMarker(); + + void RecordSnapshot(int Tick, const void *pData, int Size); + void RecordMessage(const void *pData, int Size); + + bool IsRecording() const { return m_File != 0; } + + int Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; } +}; + +class CDemoPlayer : public IDemoPlayer +{ +public: + class IListener + { + public: + virtual ~IListener() {} + virtual void OnDemoPlayerSnapshot(void *pData, int Size) = 0; + virtual void OnDemoPlayerMessage(void *pData, int Size) = 0; + }; + + struct CPlaybackInfo + { + CDemoHeader m_Header; + + IDemoPlayer::CInfo m_Info; + + int64 m_LastUpdate; + int64 m_CurrentTime; + + int m_SeekablePoints; + + int m_NextTick; + int m_PreviousTick; + + float m_IntraTick; + float m_TickTime; + }; + +private: + IListener *m_pListener; + + + // Playback + struct CKeyFrame + { + long m_Filepos; + int m_Tick; + }; + + struct CKeyFrameSearch + { + CKeyFrame m_Frame; + CKeyFrameSearch *m_pNext; + }; + + class IConsole *m_pConsole; + class IStorage *m_pStorage; + CHuffman m_Huffman; + IOHANDLE m_File; + char m_aFilename[256]; + char m_aErrorMsg[256]; + CKeyFrame *m_pKeyFrames; + + CPlaybackInfo m_Info; + int m_DemoType; + unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; + int m_LastSnapshotDataSize; + class CSnapshotDelta *m_pSnapshotDelta; + + int ReadChunkHeader(int *pType, int *pSize, int *pTick); + void DoTick(); + void ScanFile(); + +public: + + CDemoPlayer(class CSnapshotDelta *pSnapshotDelta); + void Init(class IConsole *pConsole, class IStorage *pStorage); + void SetListener(IListener *pListener); + + const char *Load(const char *pFilename, int StorageType, const char *pNetversion); + int Play(); + void Pause(); + void Unpause(); + int Stop(); + void SetSpeed(float Speed); + int SetPos(float Percent); + int SetPos(int WantedTick); + const CInfo *BaseInfo() const { return &m_Info.m_Info; } + void GetDemoName(char *pBuffer, int BufferSize) const; + bool GetDemoInfo(const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const; + int GetDemoType() const; + + int Update(); + + const CPlaybackInfo *Info() const { return &m_Info; } + int IsPlaying() const { return m_File != 0; } +}; + +#endif diff --git a/src/engine/shared/econ.cpp b/src/engine/shared/econ.cpp new file mode 100644 index 000000000..6f9eafe6f --- /dev/null +++ b/src/engine/shared/econ.cpp @@ -0,0 +1,221 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include "econ.h" +#include "netban.h" + + +int CEcon::NewClientCallback(int ClientID, void *pUser) +{ + CEcon *pThis = (CEcon *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "client accepted. cid=%d addr=%s'", ClientID, aAddrStr); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); + + pThis->m_aClients[ClientID].m_State = CClient::STATE_CONNECTED; + pThis->m_aClients[ClientID].m_TimeConnected = time_get(); + pThis->m_aClients[ClientID].m_AuthTries = 0; + + pThis->m_NetConsole.Send(ClientID, "Enter password:"); + return 0; +} + +int CEcon::DelClientCallback(int ClientID, const char *pReason, void *pUser) +{ + CEcon *pThis = (CEcon *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); + + pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; + return 0; +} + +void CEcon::SendLineCB(const char *pLine, void *pUserData, bool Highlighted) +{ + static_cast(pUserData)->Send(-1, pLine); +} + +void CEcon::ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CEcon *pThis = static_cast(pUserData); + pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); + } +} + +void CEcon::ConchainEconLingerUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CEcon *pThis = static_cast(pUserData); + pThis->m_NetConsole.SetLingerState(pResult->GetInteger(0)); + } +} + +void CEcon::ConLogout(IConsole::IResult *pResult, void *pUserData) +{ + CEcon *pThis = static_cast(pUserData); + + if(pThis->m_UserClientID >= 0 && pThis->m_UserClientID < NET_MAX_CONSOLE_CLIENTS && pThis->m_aClients[pThis->m_UserClientID].m_State != CClient::STATE_EMPTY) + pThis->m_NetConsole.Drop(pThis->m_UserClientID, "Logout"); +} + +void CEcon::Init(CConfig *pConfig, IConsole *pConsole, CNetBan *pNetBan) +{ + m_pConfig = pConfig; + m_pConsole = pConsole; + m_pNetBan = pNetBan; + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + m_aClients[i].m_State = CClient::STATE_EMPTY; + + SetDefaultValues(); +} + +void CEcon::SetDefaultValues() +{ + m_Ready = false; + m_LastOpenTry = 0; + m_UserClientID = -1; +} + +bool CEcon::Open() +{ + if(m_pConfig->m_EcPort == 0 || m_pConfig->m_EcPassword[0] == 0) + return false; + + int64 Now = time_get(); + if(m_LastOpenTry + 60 * time_freq() > Now) // try again every 60s + return false; + + NETADDR BindAddr; + if(m_pConfig->m_EcBindaddr[0] && net_host_lookup(m_pConfig->m_EcBindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // got bindaddr + BindAddr.type = NETTYPE_ALL; + BindAddr.port = m_pConfig->m_EcPort; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = m_pConfig->m_EcPort; + } + + if(m_NetConsole.Open(BindAddr, m_pNetBan, NewClientCallback, DelClientCallback, this)) + { + m_Ready = true; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "bound to %s:%d", m_pConfig->m_EcBindaddr, m_pConfig->m_EcPort); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", aBuf); + m_NetConsole.SetLingerState(m_pConfig->m_NetTcpAbortOnClose); + + Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this); + Console()->Chain("net_tcp_abort_on_close", ConchainEconLingerUpdate, this); + m_PrintCBIndex = Console()->RegisterPrintCallback(m_pConfig->m_EcOutputLevel, SendLineCB, this); + + Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ"); + return true; + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", "couldn't open socket. port might already be in use"); + + m_LastOpenTry = Now; + return false; +} + +void CEcon::Update() +{ + if(!m_Ready && !Open()) + return; + + m_NetConsole.Update(); + + char aBuf[NET_MAX_PACKETSIZE]; + int ClientID; + + while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID)) + { + dbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, "got message from empty slot"); + if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED) + { + if(str_comp(aBuf, m_pConfig->m_EcPassword) == 0) + { + m_aClients[ClientID].m_State = CClient::STATE_AUTHED; + m_NetConsole.Send(ClientID, "Authentication successful. External console access granted."); + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + str_format(aBuf, sizeof(aBuf), "cid=%d addr=%s authed", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", aBuf); + } + else + { + m_aClients[ClientID].m_AuthTries++; + char aMsg[128]; + str_format(aMsg, sizeof(aMsg), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES); + m_NetConsole.Send(ClientID, aMsg); + if(m_aClients[ClientID].m_AuthTries >= MAX_AUTH_TRIES) + { + if(m_pConfig->m_EcBantime) + m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), m_pConfig->m_EcBantime*60, "Too many authentication tries"); + m_NetConsole.Drop(ClientID, "Too many authentication tries"); + } + } + } + else if(m_aClients[ClientID].m_State == CClient::STATE_AUTHED) + { + char aFormatted[256]; + str_format(aFormatted, sizeof(aFormatted), "cid=%d cmd='%s'", ClientID, aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aFormatted); + m_UserClientID = ClientID; + Console()->ExecuteLine(aBuf); + m_UserClientID = -1; + } + } + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; ++i) + { + if(m_aClients[i].m_State == CClient::STATE_CONNECTED && + time_get() > m_aClients[i].m_TimeConnected + m_pConfig->m_EcAuthTimeout * time_freq()) + m_NetConsole.Drop(i, "authentication timeout"); + } +} + +void CEcon::Send(int ClientID, const char *pLine) +{ + if(!m_Ready) + return; + + if(ClientID == -1) + { + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aClients[i].m_State == CClient::STATE_AUTHED) + m_NetConsole.Send(i, pLine); + } + } + else if(ClientID >= 0 && ClientID < NET_MAX_CONSOLE_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_AUTHED) + m_NetConsole.Send(ClientID, pLine); +} + +void CEcon::Shutdown() +{ + if(!m_Ready) + return; + + m_NetConsole.Close(); + SetDefaultValues(); +} diff --git a/src/engine/shared/econ.h b/src/engine/shared/econ.h new file mode 100644 index 000000000..78212baee --- /dev/null +++ b/src/engine/shared/econ.h @@ -0,0 +1,62 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_ECON_H +#define ENGINE_SHARED_ECON_H + +#include "network.h" + + +class CEcon +{ + enum + { + MAX_AUTH_TRIES=3, + }; + + class CClient + { + public: + enum + { + STATE_EMPTY=0, + STATE_CONNECTED, + STATE_AUTHED, + }; + + int m_State; + int64 m_TimeConnected; + int m_AuthTries; + }; + CClient m_aClients[NET_MAX_CONSOLE_CLIENTS]; + + CConfig *m_pConfig; + IConsole *m_pConsole; + CNetBan *m_pNetBan; + CNetConsole m_NetConsole; + + bool m_Ready; + int64 m_LastOpenTry; + int m_PrintCBIndex; + int m_UserClientID; + + void SetDefaultValues(); + + static void SendLineCB(const char *pLine, void *pUserData, bool Highlighted); + static void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainEconLingerUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConLogout(IConsole::IResult *pResult, void *pUserData); + + static int NewClientCallback(int ClientID, void *pUser); + static int DelClientCallback(int ClientID, const char *pReason, void *pUser); + +public: + IConsole *Console() { return m_pConsole; } + + void Init(CConfig *pConfig, IConsole *pConsole, class CNetBan *pNetBan); + bool Open(); + void Update(); + void Send(int ClientID, const char *pLine); + void Shutdown(); +}; + +#endif diff --git a/src/engine/shared/engine.cpp b/src/engine/shared/engine.cpp new file mode 100644 index 000000000..62a7f06cd --- /dev/null +++ b/src/engine/shared/engine.cpp @@ -0,0 +1,176 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include // srand + +#include + +#include +#include +#include +#include +#include + + +static int HostLookupThread(void *pUser) +{ + CHostLookup *pLookup = (CHostLookup *)pUser; + return net_host_lookup(pLookup->m_aHostname, &pLookup->m_Addr, pLookup->m_Nettype); +} + +class CEngine : public IEngine +{ +public: + CConfig *m_pConfig; + IConsole *m_pConsole; + IStorage *m_pStorage; + bool m_Logging; + IOHANDLE m_DataLogSent; + IOHANDLE m_DataLogRecv; + const char *m_pAppname; + + static void Con_DbgLognetwork(IConsole::IResult *pResult, void *pUserData) + { + CEngine *pEngine = static_cast(pUserData); + + if(pEngine->m_Logging) + { + pEngine->StopLogging(); + } + else + { + char aBuf[32]; + str_timestamp(aBuf, sizeof(aBuf)); + char aFilenameSent[128], aFilenameRecv[128]; + str_format(aFilenameSent, sizeof(aFilenameSent), "dumps/%s_network_sent_%s.txt", pEngine->m_pAppname, aBuf); + str_format(aFilenameRecv, sizeof(aFilenameRecv), "dumps/%s_network_recv_%s.txt", pEngine->m_pAppname, aBuf); + pEngine->StartLogging(pEngine->m_pStorage->OpenFile(aFilenameSent, IOFLAG_WRITE, IStorage::TYPE_SAVE), + pEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE)); + } + } + + CEngine(const char *pAppname) + { + srand(time_get()); + dbg_logger_stdout(); + dbg_logger_debugger(); + + // + dbg_msg("engine", "running on %s-%s-%s", CONF_FAMILY_STRING, CONF_PLATFORM_STRING, CONF_ARCH_STRING); + #ifdef CONF_ARCH_ENDIAN_LITTLE + dbg_msg("engine", "arch is little endian"); + #elif defined(CONF_ARCH_ENDIAN_BIG) + dbg_msg("engine", "arch is big endian"); + #else + dbg_msg("engine", "unknown endian"); + #endif + + m_JobPool.Init(1); + + m_DataLogSent = 0; + m_DataLogRecv = 0; + m_Logging = false; + m_pAppname = pAppname; + } + + ~CEngine() + { + StopLogging(); + } + + void Init() + { + m_pConfig = Kernel()->RequestInterface()->Values(); + m_pConsole = Kernel()->RequestInterface(); + m_pStorage = Kernel()->RequestInterface(); + + if(!m_pConsole || !m_pStorage) + return; + + m_pConsole->Register("dbg_lognetwork", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgLognetwork, this, "Log the network"); + } + + void ShutdownJobs() + { + m_JobPool.Shutdown(); + } + + void InitLogfile() + { + // open logfile if needed + if(m_pConfig->m_Logfile[0]) + { + char aBuf[32]; + if(m_pConfig->m_LogfileTimestamp) + str_timestamp(aBuf, sizeof(aBuf)); + else + aBuf[0] = 0; + char aLogFilename[128]; + str_format(aLogFilename, sizeof(aLogFilename), "dumps/%s%s.txt", m_pConfig->m_Logfile, aBuf); + IOHANDLE Handle = m_pStorage->OpenFile(aLogFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(Handle) + dbg_logger_filehandle(Handle); + else + dbg_msg("engine/logfile", "failed to open '%s' for logging", aLogFilename); + } + } + + void QueryNetLogHandles(IOHANDLE *pHDLSend, IOHANDLE *pHDLRecv) + { + *pHDLSend = m_DataLogSent; + *pHDLRecv = m_DataLogRecv; + } + + void StartLogging(IOHANDLE DataLogSent, IOHANDLE DataLogRecv) + { + if(DataLogSent) + { + m_DataLogSent = DataLogSent; + dbg_msg("engine", "logging network sent packages"); + } + else + dbg_msg("engine", "failed to start logging network sent packages"); + + if(DataLogRecv) + { + m_DataLogRecv = DataLogRecv; + dbg_msg("engine", "logging network recv packages"); + } + else + dbg_msg("engine", "failed to start logging network recv packages"); + + m_Logging = true; + } + + void StopLogging() + { + if(m_DataLogSent) + { + dbg_msg("engine", "stopped logging network sent packages"); + io_close(m_DataLogSent); + m_DataLogSent = 0; + } + if(m_DataLogRecv) + { + dbg_msg("engine", "stopped logging network recv packages"); + io_close(m_DataLogRecv); + m_DataLogRecv = 0; + } + m_Logging = false; + } + + void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) + { + str_copy(pLookup->m_aHostname, pHostname, sizeof(pLookup->m_aHostname)); + pLookup->m_Nettype = Nettype; + AddJob(&pLookup->m_Job, HostLookupThread, pLookup); + } + + void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) + { + if(m_pConfig->m_Debug) + dbg_msg("engine", "job added"); + m_JobPool.Add(pJob, pfnFunc, pData); + } +}; + +IEngine *CreateEngine(const char *pAppname) { return new CEngine(pAppname); } diff --git a/src/engine/shared/filecollection.cpp b/src/engine/shared/filecollection.cpp new file mode 100644 index 000000000..9a0ed2caf --- /dev/null +++ b/src/engine/shared/filecollection.cpp @@ -0,0 +1,186 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include + +#include + +#include "filecollection.h" + +bool CFileCollection::IsFilenameValid(const char *pFilename) +{ + if(str_length(pFilename) != m_FileDescLength+TIMESTAMP_LENGTH+m_FileExtLength || + str_comp_num(pFilename, m_aFileDesc, m_FileDescLength) || + str_comp(pFilename+m_FileDescLength+TIMESTAMP_LENGTH, m_aFileExt)) + return false; + + pFilename += m_FileDescLength; + if(pFilename[0] == '_' && + pFilename[1] >= '0' && pFilename[1] <= '9' && + pFilename[2] >= '0' && pFilename[2] <= '9' && + pFilename[3] >= '0' && pFilename[3] <= '9' && + pFilename[4] >= '0' && pFilename[4] <= '9' && + pFilename[5] == '-' && + pFilename[6] >= '0' && pFilename[6] <= '9' && + pFilename[7] >= '0' && pFilename[7] <= '9' && + pFilename[8] == '-' && + pFilename[9] >= '0' && pFilename[9] <= '9' && + pFilename[10] >= '0' && pFilename[10] <= '9' && + pFilename[11] == '_' && + pFilename[12] >= '0' && pFilename[12] <= '9' && + pFilename[13] >= '0' && pFilename[13] <= '9' && + pFilename[14] == '-' && + pFilename[15] >= '0' && pFilename[15] <= '9' && + pFilename[16] >= '0' && pFilename[16] <= '9' && + pFilename[17] == '-' && + pFilename[18] >= '0' && pFilename[18] <= '9' && + pFilename[19] >= '0' && pFilename[19] <= '9') + return true; + + return false; +} + +int64 CFileCollection::ExtractTimestamp(const char *pTimestring) +{ + int64 Timestamp = pTimestring[0]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[1]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[2]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[3]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[5]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[6]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[8]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[9]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[11]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[12]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[14]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[15]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[17]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[18]-'0'; + + return Timestamp; +} + +void CFileCollection::BuildTimestring(int64 Timestamp, char *pTimestring) +{ + pTimestring[19] = 0; + pTimestring[18] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[17] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[16] = '-'; + pTimestring[15] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[14] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[13] = '-'; + pTimestring[12] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[11] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[10] = '_'; + pTimestring[9] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[8] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[7] = '-'; + pTimestring[6] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[5] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[4] = '-'; + pTimestring[3] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[2] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[1] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[0] = (Timestamp&0xF)+'0'; +} + +void CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries) +{ + mem_zero(m_aTimestamps, sizeof(m_aTimestamps)); + m_NumTimestamps = 0; + m_MaxEntries = clamp(MaxEntries, 1, static_cast(MAX_ENTRIES)); + str_copy(m_aFileDesc, pFileDesc, sizeof(m_aFileDesc)); + m_FileDescLength = str_length(m_aFileDesc); + str_copy(m_aFileExt, pFileExt, sizeof(m_aFileExt)); + m_FileExtLength = str_length(m_aFileExt); + str_copy(m_aPath, pPath, sizeof(m_aPath)); + m_pStorage = pStorage; + + m_pStorage->ListDirectory(IStorage::TYPE_SAVE, m_aPath, FilelistCallback, this); +} + +void CFileCollection::AddEntry(int64 Timestamp) +{ + if(m_NumTimestamps == 0) + { + // empty list + m_aTimestamps[m_NumTimestamps++] = Timestamp; + } + else + { + // remove old file + if(m_NumTimestamps == m_MaxEntries) + { + char aBuf[IO_MAX_PATH_LENGTH]; + char aTimestring[TIMESTAMP_LENGTH]; + BuildTimestring(m_aTimestamps[0], aTimestring); + str_format(aBuf, sizeof(aBuf), "%s/%s_%s%s", m_aPath, m_aFileDesc, aTimestring, m_aFileExt); + m_pStorage->RemoveFile(aBuf, IStorage::TYPE_SAVE); + } + + // add entry to the sorted list + if(m_aTimestamps[0] > Timestamp) + { + // first entry + if(m_NumTimestamps < m_MaxEntries) + { + mem_move(m_aTimestamps+1, m_aTimestamps, m_NumTimestamps*sizeof(int64)); + m_aTimestamps[0] = Timestamp; + ++m_NumTimestamps; + } + } + else if(m_aTimestamps[m_NumTimestamps-1] <= Timestamp) + { + // last entry + if(m_NumTimestamps == m_MaxEntries) + { + mem_move(m_aTimestamps, m_aTimestamps+1, (m_NumTimestamps-1)*sizeof(int64)); + m_aTimestamps[m_NumTimestamps-1] = Timestamp; + } + else + m_aTimestamps[m_NumTimestamps++] = Timestamp; + } + else + { + // middle entry + int Left = 0, Right = m_NumTimestamps-1; + while(Right-Left > 1) + { + int Mid = (Left+Right)/2; + if(m_aTimestamps[Mid] > Timestamp) + Right = Mid; + else + Left = Mid; + } + + if(m_NumTimestamps == m_MaxEntries) + { + mem_move(m_aTimestamps, m_aTimestamps+1, (Right-1)*sizeof(int64)); + m_aTimestamps[Right-1] = Timestamp; + } + else + { + mem_move(m_aTimestamps+Right+1, m_aTimestamps+Right, (m_NumTimestamps-Right)*sizeof(int64)); + m_aTimestamps[Right] = Timestamp; + ++m_NumTimestamps; + } + } + } +} + +int CFileCollection::FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser) +{ + CFileCollection *pThis = static_cast(pUser); + + // check for valid file name format + if(IsDir || !pThis->IsFilenameValid(pFilename)) + return 0; + + // extract the timestamp + int64 Timestamp = pThis->ExtractTimestamp(pFilename+pThis->m_FileDescLength+1); + + // add the entry + pThis->AddEntry(Timestamp); + + return 0; +} diff --git a/src/engine/shared/filecollection.h b/src/engine/shared/filecollection.h new file mode 100644 index 000000000..47206c248 --- /dev/null +++ b/src/engine/shared/filecollection.h @@ -0,0 +1,35 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_FILECOLLECTION_H +#define ENGINE_SHARED_FILECOLLECTION_H + +class CFileCollection +{ + enum + { + MAX_ENTRIES=1000, + TIMESTAMP_LENGTH=20, // _YYYY-MM-DD_HH-MM-SS + }; + + int64 m_aTimestamps[MAX_ENTRIES]; + int m_NumTimestamps; + int m_MaxEntries; + char m_aFileDesc[128]; + int m_FileDescLength; + char m_aFileExt[32]; + int m_FileExtLength; + char m_aPath[IO_MAX_PATH_LENGTH]; + IStorage *m_pStorage; + + bool IsFilenameValid(const char *pFilename); + int64 ExtractTimestamp(const char *pTimestring); + void BuildTimestring(int64 Timestamp, char *pTimestring); + +public: + void Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries); + void AddEntry(int64 Timestamp); + + static int FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser); +}; + +#endif diff --git a/src/engine/shared/huffman.cpp b/src/engine/shared/huffman.cpp new file mode 100644 index 000000000..cce241bbd --- /dev/null +++ b/src/engine/shared/huffman.cpp @@ -0,0 +1,298 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include "huffman.h" + + +static const unsigned gs_aFreqTable[256 + 1] = { + 1 << 30,4545,2657,431,1950,919,444,482,2244,617,838,542,715,1814,304,240,754,212,647,186, + 283,131,146,166,543,164,167,136,179,859,363,113,157,154,204,108,137,180,202,176, + 872,404,168,134,151,111,113,109,120,126,129,100,41,20,16,22,18,18,17,19, + 16,37,13,21,362,166,99,78,95,88,81,70,83,284,91,187,77,68,52,68, + 59,66,61,638,71,157,50,46,69,43,11,24,13,19,10,12,12,20,14,9, + 20,20,10,10,15,15,12,12,7,19,15,14,13,18,35,19,17,14,8,5, + 15,17,9,15,14,18,8,10,2173,134,157,68,188,60,170,60,194,62,175,71, + 148,67,167,78,211,67,156,69,1674,90,174,53,147,89,181,51,174,63,163,80, + 167,94,128,122,223,153,218,77,200,110,190,73,174,69,145,66,277,143,141,60, + 136,53,180,57,142,57,158,61,166,112,152,92,26,22,21,28,20,26,30,21, + 32,27,20,17,23,21,30,22,22,21,27,25,17,27,23,18,39,26,15,21, + 12,18,18,27,20,18,15,19,11,17,33,12,18,15,19,18,16,26,17,18, + 9,10,25,22,22,17,20,16,6,16,15,20,14,18,24,335,1517 }; + +struct CHuffmanConstructNode +{ + unsigned short m_NodeId; + int m_Frequency; +}; + +void CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth) +{ + if(pNode->m_aLeafs[1] != 0xffff) + Setbits_r(&m_aNodes[pNode->m_aLeafs[1]], Bits|(1<m_aLeafs[0] != 0xffff) + Setbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth+1); + + if(pNode->m_NumBits) + { + pNode->m_Bits = Bits; + pNode->m_NumBits = Depth; + } +} + +// TODO: this should be something faster, but it's enough for now +static void BubbleSort(CHuffmanConstructNode **ppList, int Size) +{ + int Changed = 1; + CHuffmanConstructNode *pTemp; + + while(Changed) + { + Changed = 0; + for(int i = 0; i < Size-1; i++) + { + if(ppList[i]->m_Frequency < ppList[i+1]->m_Frequency) + { + pTemp = ppList[i]; + ppList[i] = ppList[i+1]; + ppList[i+1] = pTemp; + Changed = 1; + } + } + Size--; + } +} + +void CHuffman::ConstructTree(const unsigned *pFrequencies) +{ + CHuffmanConstructNode aNodesLeftStorage[HUFFMAN_MAX_SYMBOLS]; + CHuffmanConstructNode *apNodesLeft[HUFFMAN_MAX_SYMBOLS]; + int NumNodesLeft = HUFFMAN_MAX_SYMBOLS; + + // add the symbols + for(int i = 0; i < HUFFMAN_MAX_SYMBOLS; i++) + { + m_aNodes[i].m_NumBits = 0xFFFFFFFF; + m_aNodes[i].m_Symbol = i; + m_aNodes[i].m_aLeafs[0] = 0xffff; + m_aNodes[i].m_aLeafs[1] = 0xffff; + + if(i == HUFFMAN_EOF_SYMBOL) + aNodesLeftStorage[i].m_Frequency = 1; + else + aNodesLeftStorage[i].m_Frequency = pFrequencies[i]; + aNodesLeftStorage[i].m_NodeId = i; + apNodesLeft[i] = &aNodesLeftStorage[i]; + + } + + m_NumNodes = HUFFMAN_MAX_SYMBOLS; + + // construct the table + while(NumNodesLeft > 1) + { + // we can't rely on stdlib's qsort for this, it can generate different results on different implementations + BubbleSort(apNodesLeft, NumNodesLeft); + + m_aNodes[m_NumNodes].m_NumBits = 0; + m_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft-1]->m_NodeId; + m_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft-2]->m_NodeId; + apNodesLeft[NumNodesLeft-2]->m_NodeId = m_NumNodes; + apNodesLeft[NumNodesLeft-2]->m_Frequency = apNodesLeft[NumNodesLeft-1]->m_Frequency + apNodesLeft[NumNodesLeft-2]->m_Frequency; + + m_NumNodes++; + NumNodesLeft--; + } + + // set start node + m_pStartNode = &m_aNodes[m_NumNodes-1]; + + // build symbol bits + Setbits_r(m_pStartNode, 0, 0); +} + +void CHuffman::Init(const unsigned *pFrequencies) +{ + // make sure to cleanout every thing + mem_zero(this, sizeof(*this)); + + // construct the tree + if(!pFrequencies) + pFrequencies = gs_aFreqTable; + ConstructTree(pFrequencies); + + // build decode LUT + for(int i = 0; i < HUFFMAN_LUTSIZE; i++) + { + unsigned Bits = i; + int k; + CNode *pNode = m_pStartNode; + for(k = 0; k < HUFFMAN_LUTBITS; k++) + { + pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + Bits >>= 1; + + if(!pNode) + break; + + if(pNode->m_NumBits) + { + m_apDecodeLut[i] = pNode; + break; + } + } + + if(k == HUFFMAN_LUTBITS) + m_apDecodeLut[i] = pNode; + } + +} + +//*************************************************************** +int CHuffman::Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize) +{ + // this macro loads a symbol for a byte into bits and bitcount +#define HUFFMAN_MACRO_LOADSYMBOL(Sym) \ + Bits |= m_aNodes[Sym].m_Bits << Bitcount; \ + Bitcount += m_aNodes[Sym].m_NumBits; + + // this macro writes the symbol stored in bits and bitcount to the dst pointer +#define HUFFMAN_MACRO_WRITE() \ + while(Bitcount >= 8) \ + { \ + *pDst++ = (unsigned char)(Bits&0xff); \ + if(pDst == pDstEnd) \ + return -1; \ + Bits >>= 8; \ + Bitcount -= 8; \ + } + + // setup buffer pointers + const unsigned char *pSrc = (const unsigned char *)pInput; + const unsigned char *pSrcEnd = pSrc + InputSize; + unsigned char *pDst = (unsigned char *)pOutput; + unsigned char *pDstEnd = pDst + OutputSize; + + // symbol variables + unsigned Bits = 0; + unsigned Bitcount = 0; + + // make sure that we have data that we want to compress + if(InputSize) + { + // {A} load the first symbol + int Symbol = *pSrc++; + + while(pSrc != pSrcEnd) + { + // {B} load the symbol + HUFFMAN_MACRO_LOADSYMBOL(Symbol) + + // {C} fetch next symbol, this is done here because it will reduce dependency in the code + Symbol = *pSrc++; + + // {B} write the symbol loaded at + HUFFMAN_MACRO_WRITE() + } + + // write the last symbol loaded from {C} or {A} in the case of only 1 byte input buffer + HUFFMAN_MACRO_LOADSYMBOL(Symbol) + HUFFMAN_MACRO_WRITE() + } + + // write EOF symbol + HUFFMAN_MACRO_LOADSYMBOL(HUFFMAN_EOF_SYMBOL) + HUFFMAN_MACRO_WRITE() + + // write out the last bits + *pDst++ = Bits; + + // return the size of the output + return (int)(pDst - (const unsigned char *)pOutput); + + // remove macros +#undef HUFFMAN_MACRO_LOADSYMBOL +#undef HUFFMAN_MACRO_WRITE +} + +//*************************************************************** +int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize) +{ + // setup buffer pointers + unsigned char *pDst = (unsigned char *)pOutput; + unsigned char *pSrc = (unsigned char *)pInput; + unsigned char *pDstEnd = pDst + OutputSize; + unsigned char *pSrcEnd = pSrc + InputSize; + + unsigned Bits = 0; + unsigned Bitcount = 0; + + CNode *pEof = &m_aNodes[HUFFMAN_EOF_SYMBOL]; + CNode *pNode = 0; + + while(1) + { + // {A} try to load a node now, this will reduce dependency at location {D} + pNode = 0; + if(Bitcount >= HUFFMAN_LUTBITS) + pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; + + // {B} fill with new bits + while(Bitcount < 24 && pSrc != pSrcEnd) + { + Bits |= (*pSrc++) << Bitcount; + Bitcount += 8; + } + + // {C} load symbol now if we didn't that earlier at location {A} + if(!pNode) + pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; + + if(!pNode) + return -1; + + // {D} check if we hit a symbol already + if(pNode->m_NumBits) + { + // remove the bits for that symbol + Bits >>= pNode->m_NumBits; + Bitcount -= pNode->m_NumBits; + } + else + { + // remove the bits that the lut checked up for us + Bits >>= HUFFMAN_LUTBITS; + Bitcount -= HUFFMAN_LUTBITS; + + // walk the tree bit by bit + while(1) + { + // traverse tree + pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + + // remove bit + Bitcount--; + Bits >>= 1; + + // check if we hit a symbol + if(pNode->m_NumBits) + break; + + // no more bits, decoding error + if(Bitcount == 0) + return -1; + } + } + + // check for eof + if(pNode == pEof) + break; + + // output character + if(pDst == pDstEnd) + return -1; + *pDst++ = pNode->m_Symbol; + } + + // return the size of the decompressed buffer + return (int)(pDst - (const unsigned char *)pOutput); +} diff --git a/src/engine/shared/huffman.h b/src/engine/shared/huffman.h new file mode 100644 index 000000000..96628db9c --- /dev/null +++ b/src/engine/shared/huffman.h @@ -0,0 +1,91 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_HUFFMAN_H +#define ENGINE_SHARED_HUFFMAN_H + + + +class CHuffman +{ + enum + { + HUFFMAN_EOF_SYMBOL = 256, + + HUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1, + HUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1, + + HUFFMAN_LUTBITS = 10, + HUFFMAN_LUTSIZE = (1< +#include "jobs.h" + +CJobPool::CJobPool() +{ + // empty the pool + m_NumThreads = 0; + m_Shutdown = false; + m_Lock = lock_create(); + m_pFirstJob = 0; + m_pLastJob = 0; +} + +CJobPool::~CJobPool() +{ + Shutdown(); +} + +void CJobPool::Shutdown() +{ + if(m_Shutdown) + return; + + m_Shutdown = true; + for(int i = 0; i < m_NumThreads; i++) + { + thread_wait(m_apThreads[i]); + thread_destroy(m_apThreads[i]); + } + lock_destroy(m_Lock); +} + +void CJobPool::WorkerThread(void *pUser) +{ + CJobPool *pPool = (CJobPool *)pUser; + + while(!pPool->m_Shutdown) + { + CJob *pJob = 0; + + // fetch job from queue + lock_wait(pPool->m_Lock); + if(pPool->m_pFirstJob) + { + pJob = pPool->m_pFirstJob; + pPool->m_pFirstJob = pPool->m_pFirstJob->m_pNext; + if(pPool->m_pFirstJob) + pPool->m_pFirstJob->m_pPrev = 0; + else + pPool->m_pLastJob = 0; + } + lock_unlock(pPool->m_Lock); + + // do the job if we have one + if(pJob) + { + pJob->m_Status = CJob::STATE_RUNNING; + pJob->m_Result = pJob->m_pfnFunc(pJob->m_pFuncData); + pJob->m_Status = CJob::STATE_DONE; + } + else + thread_sleep(10); + } + +} + +int CJobPool::Init(int NumThreads) +{ + // start threads + m_NumThreads = NumThreads > MAX_THREADS ? MAX_THREADS : NumThreads; + for(int i = 0; i < m_NumThreads; i++) + m_apThreads[i] = thread_init(WorkerThread, this); + return 0; +} + +int CJobPool::Add(CJob *pJob, JOBFUNC pfnFunc, void *pData) +{ + mem_zero(pJob, sizeof(CJob)); + pJob->m_pfnFunc = pfnFunc; + pJob->m_pFuncData = pData; + + lock_wait(m_Lock); + + // add job to queue + pJob->m_pPrev = m_pLastJob; + if(m_pLastJob) + m_pLastJob->m_pNext = pJob; + m_pLastJob = pJob; + if(!m_pFirstJob) + m_pFirstJob = pJob; + + lock_unlock(m_Lock); + return 0; +} + diff --git a/src/engine/shared/jobs.h b/src/engine/shared/jobs.h new file mode 100644 index 000000000..e293ccac7 --- /dev/null +++ b/src/engine/shared/jobs.h @@ -0,0 +1,63 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_JOBS_H +#define ENGINE_SHARED_JOBS_H +typedef int (*JOBFUNC)(void *pData); + +class CJobPool; + +class CJob +{ + friend class CJobPool; + + CJob *m_pPrev; + CJob *m_pNext; + + volatile int m_Status; + volatile int m_Result; + + JOBFUNC m_pfnFunc; + void *m_pFuncData; +public: + CJob() + { + m_Status = STATE_DONE; + m_pFuncData = 0; + } + + enum + { + STATE_PENDING=0, + STATE_RUNNING, + STATE_DONE + }; + + int Status() const { return m_Status; } + int Result() const {return m_Result; } +}; + +class CJobPool +{ + enum + { + MAX_THREADS=32 + }; + int m_NumThreads; + void *m_apThreads[MAX_THREADS]; + volatile bool m_Shutdown; + + LOCK m_Lock; + CJob *m_pFirstJob; + CJob *m_pLastJob; + + static void WorkerThread(void *pUser); + +public: + CJobPool(); + ~CJobPool(); + + int Init(int NumThreads); + void Shutdown(); + int Add(CJob *pJob, JOBFUNC pfnFunc, void *pData); +}; +#endif diff --git a/src/engine/shared/jsonwriter.cpp b/src/engine/shared/jsonwriter.cpp new file mode 100644 index 000000000..ae1936c9d --- /dev/null +++ b/src/engine/shared/jsonwriter.cpp @@ -0,0 +1,220 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "jsonwriter.h" + +static char EscapeJsonChar(char c) +{ + switch(c) + { + case '\"': return '\"'; + case '\\': return '\\'; + case '\b': return 'b'; + case '\n': return 'n'; + case '\r': return 'r'; + case '\t': return 't'; + // Don't escape '\f', who uses that. :) + default: return 0; + } +} + +CJsonWriter::CJsonWriter(IOHANDLE IO) +{ + m_IO = IO; + m_NumStates = 0; // no root created yet + m_Indentation = 0; +} + +CJsonWriter::~CJsonWriter() +{ + io_write_newline(m_IO); + io_close(m_IO); +} + +void CJsonWriter::BeginObject() +{ + dbg_assert(CanWriteDatatype(), "Cannot write object at this position"); + WriteIndent(false); + WriteInternal("{"); + PushState(STATE_OBJECT); +} + +void CJsonWriter::EndObject() +{ + dbg_assert(TopState()->m_Kind == STATE_OBJECT, "Cannot end object here"); + PopState(); + CompleteDataType(); + WriteIndent(true); + WriteInternal("}"); + +} + +void CJsonWriter::BeginArray() +{ + dbg_assert(CanWriteDatatype(), "Cannot write array at this position"); + WriteIndent(false); + WriteInternal("["); + PushState(STATE_ARRAY); +} + +void CJsonWriter::EndArray() +{ + dbg_assert(TopState()->m_Kind == STATE_ARRAY, "Cannot end array here"); + PopState(); + CompleteDataType(); + WriteIndent(true); + WriteInternal("]"); +} + +void CJsonWriter::WriteAttribute(const char *pName) +{ + dbg_assert(TopState()->m_Kind == STATE_OBJECT, "Attribute can only be written inside of objects"); + WriteIndent(false); + WriteInternalEscaped(pName); + WriteInternal(": "); + PushState(STATE_ATTRIBUTE); +} + +void CJsonWriter::WriteStrValue(const char *pValue) +{ + dbg_assert(CanWriteDatatype(), "Cannot write value at this position"); + WriteIndent(false); + WriteInternalEscaped(pValue); + CompleteDataType(); +} + +void CJsonWriter::WriteIntValue(int Value) +{ + dbg_assert(CanWriteDatatype(), "Cannot write value at this position"); + WriteIndent(false); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "%d", Value); + WriteInternal(aBuf); + CompleteDataType(); +} + +void CJsonWriter::WriteBoolValue(bool Value) +{ + dbg_assert(CanWriteDatatype(), "Cannot write value at this position"); + WriteIndent(false); + WriteInternal(Value ? "true" : "false"); + CompleteDataType(); +} + +void CJsonWriter::WriteNullValue() +{ + dbg_assert(CanWriteDatatype(), "Cannot write value at this position"); + WriteIndent(false); + WriteInternal("null"); + CompleteDataType(); +} + +bool CJsonWriter::CanWriteDatatype() +{ + return m_NumStates == 0 + || TopState()->m_Kind == STATE_ARRAY + || TopState()->m_Kind == STATE_ATTRIBUTE; +} + +inline void CJsonWriter::WriteInternal(const char *pStr) +{ + io_write(m_IO, pStr, str_length(pStr)); +} + +void CJsonWriter::WriteInternalEscaped(const char *pStr) +{ + WriteInternal("\""); + int UnwrittenFrom = 0; + int Length = str_length(pStr); + for(int i = 0; i < Length; i++) + { + char SimpleEscape = EscapeJsonChar(pStr[i]); + // Assuming ASCII/UTF-8, exactly everything below 0x20 is a + // control character. + bool NeedsEscape = SimpleEscape || (unsigned char)pStr[i] < 0x20; + if(NeedsEscape) + { + if(i - UnwrittenFrom > 0) + { + io_write(m_IO, pStr + UnwrittenFrom, i - UnwrittenFrom); + } + + if(SimpleEscape) + { + char aStr[2]; + aStr[0] = '\\'; + aStr[1] = SimpleEscape; + io_write(m_IO, aStr, sizeof(aStr)); + } + else + { + char aStr[7]; + str_format(aStr, sizeof(aStr), "\\u%04x", pStr[i]); + WriteInternal(aStr); + } + UnwrittenFrom = i + 1; + } + } + if(Length - UnwrittenFrom > 0) + { + io_write(m_IO, pStr + UnwrittenFrom, Length - UnwrittenFrom); + } + WriteInternal("\""); +} + +void CJsonWriter::WriteIndent(bool EndElement) +{ + const bool NotRootOrAttribute = m_NumStates != 0 + && TopState()->m_Kind != STATE_ATTRIBUTE; + + if(NotRootOrAttribute && !TopState()->m_Empty && !EndElement) + WriteInternal(","); + + if(NotRootOrAttribute || EndElement) + io_write_newline(m_IO); + + if(NotRootOrAttribute) + for(int i = 0; i < m_Indentation; i++) + WriteInternal("\t"); +} + +void CJsonWriter::PushState(unsigned char NewState) +{ + dbg_assert(m_NumStates < MAX_DEPTH, "max json depth exceeded"); + if(m_NumStates != 0) + { + m_aStates[m_NumStates - 1].m_Empty = false; + } + m_aStates[m_NumStates] = CState(NewState); + m_NumStates++; + if(NewState != STATE_ATTRIBUTE) + { + m_Indentation++; + } +} + +CJsonWriter::CState *CJsonWriter::TopState() +{ + dbg_assert(m_NumStates != 0, "json stack is empty"); + return &m_aStates[m_NumStates - 1]; +} + +unsigned char CJsonWriter::PopState() +{ + dbg_assert(m_NumStates != 0, "json stack is empty"); + m_NumStates--; + if(m_aStates[m_NumStates].m_Kind != STATE_ATTRIBUTE) + { + m_Indentation--; + } + return m_aStates[m_NumStates].m_Kind; +} + +void CJsonWriter::CompleteDataType() +{ + if(m_NumStates != 0 && m_aStates[m_NumStates - 1].m_Kind == STATE_ATTRIBUTE) + PopState(); // automatically complete the attribute + + if(m_NumStates != 0) + m_aStates[m_NumStates - 1].m_Empty = false; +} diff --git a/src/engine/shared/jsonwriter.h b/src/engine/shared/jsonwriter.h new file mode 100644 index 000000000..441fd5c26 --- /dev/null +++ b/src/engine/shared/jsonwriter.h @@ -0,0 +1,83 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_JSONWRITER_H +#define ENGINE_SHARED_JSONWRITER_H + +#include + +class CJsonWriter +{ + enum + { + STATE_INVALID, + STATE_OBJECT, + STATE_ARRAY, + STATE_ATTRIBUTE, + + MAX_DEPTH=16, + }; + + class CState + { + public: + unsigned char m_Kind; + bool m_Empty; + + CState(unsigned char Kind = STATE_INVALID) + { + m_Kind = Kind; + m_Empty = true; + }; + }; + + IOHANDLE m_IO; + + CState m_aStates[MAX_DEPTH]; + int m_NumStates; + int m_Indentation; + + bool CanWriteDatatype(); + inline void WriteInternal(const char *pStr); + void WriteInternalEscaped(const char *pStr); + void WriteIndent(bool EndElement); + void PushState(unsigned char NewState); + CState *TopState(); + unsigned char PopState(); + void CompleteDataType(); + +public: + // Create a new writer object without writing anything to the file yet. + // The file will automatically be closed by the destructor. + CJsonWriter(IOHANDLE IO); + ~CJsonWriter(); + + // The root is created by beginning the first datatype (object, array, value). + // The writer must not be used after ending the root, which must be unique. + + // Begin writing a new object + void BeginObject(); + // End current object + void EndObject(); + + // Begin writing a new array + void BeginArray(); + // End current array + void EndArray(); + + // Write attribute with the given name inside the current object. + // Names inside one object should be unique, but this is not checked here. + // Must be used to begin write anything inside objects and only there. + // Must be followed by a datatype for the attribute value. + void WriteAttribute(const char *pName); + + // Methods for writing value literals + // - As array values in arrays + // - As attribute values after beginning an attribute inside an object + // - As root value (only once) + void WriteStrValue(const char *pValue); + void WriteIntValue(int Value); + void WriteBoolValue(bool Value); + void WriteNullValue(); +}; + +#endif diff --git a/src/engine/shared/kernel.cpp b/src/engine/shared/kernel.cpp new file mode 100644 index 000000000..95ecddbd0 --- /dev/null +++ b/src/engine/shared/kernel.cpp @@ -0,0 +1,101 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +class CKernel : public IKernel +{ + enum + { + MAX_INTERFACES=32, + }; + + class CInterfaceInfo + { + public: + CInterfaceInfo() + { + m_aName[0] = 0; + m_pInterface = 0x0; + } + + char m_aName[64]; + IInterface *m_pInterface; + }; + + CInterfaceInfo m_aInterfaces[MAX_INTERFACES]; + int m_NumInterfaces; + + CInterfaceInfo *FindInterfaceInfo(const char *pName) + { + for(int i = 0; i < m_NumInterfaces; i++) + { + if(str_comp(pName, m_aInterfaces[i].m_aName) == 0) + return &m_aInterfaces[i]; + } + return 0x0; + } + +public: + + CKernel() + { + m_NumInterfaces = 0; + } + + + virtual bool RegisterInterfaceImpl(const char *pName, IInterface *pInterface) + { + // TODO: More error checks here + if(!pInterface) + { + dbg_msg("kernel", "ERROR: couldn't register interface %s. null pointer given", pName); + return false; + } + + if(m_NumInterfaces == MAX_INTERFACES) + { + dbg_msg("kernel", "ERROR: couldn't register interface '%s'. maximum of interfaces reached", pName); + return false; + } + + if(FindInterfaceInfo(pName) != 0) + { + dbg_msg("kernel", "ERROR: couldn't register interface '%s'. interface already exists", pName); + return false; + } + + pInterface->m_pKernel = this; + m_aInterfaces[m_NumInterfaces].m_pInterface = pInterface; + str_copy(m_aInterfaces[m_NumInterfaces].m_aName, pName, sizeof(m_aInterfaces[m_NumInterfaces].m_aName)); + m_NumInterfaces++; + + return true; + } + + virtual bool ReregisterInterfaceImpl(const char *pName, IInterface *pInterface) + { + if(FindInterfaceInfo(pName) == 0) + { + dbg_msg("kernel", "ERROR: couldn't reregister interface '%s'. interface doesn't exist", pName); + return false; + } + + pInterface->m_pKernel = this; + + return true; + } + + virtual IInterface *RequestInterfaceImpl(const char *pName) + { + CInterfaceInfo *pInfo = FindInterfaceInfo(pName); + if(!pInfo) + { + dbg_msg("kernel", "failed to find interface with the name '%s'", pName); + return 0; + } + return pInfo->m_pInterface; + } +}; + +IKernel *IKernel::Create() { return new CKernel; } diff --git a/src/engine/shared/linereader.cpp b/src/engine/shared/linereader.cpp new file mode 100644 index 000000000..7a7e7286a --- /dev/null +++ b/src/engine/shared/linereader.cpp @@ -0,0 +1,81 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "linereader.h" + +void CLineReader::Init(IOHANDLE IoHandle) +{ + m_BufferMaxSize = sizeof(m_aBuffer) - 1; + m_BufferSize = 0; + m_BufferPos = 0; + m_IO = IoHandle; +} + +const char *CLineReader::Get() +{ + unsigned LineStart = m_BufferPos; + bool CRLFBreak = false; + + while(true) + { + if(m_BufferPos >= m_BufferSize) + { + // fetch more + + // move the remaining part to the front + unsigned Left = m_BufferSize - LineStart; + + if(LineStart > m_BufferSize) + Left = 0; + if(Left) + mem_move(m_aBuffer, &m_aBuffer[LineStart], Left); + m_BufferPos = Left; + + // fill the buffer + unsigned Read = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize - m_BufferPos); + m_BufferSize = Left + Read; + LineStart = 0; + + if(!Read) + { + if(Left) + { + m_aBuffer[Left] = 0; // return the last line + m_BufferPos = Left; + m_BufferSize = Left; + return m_aBuffer; + } + else + return 0x0; // we are done! + } + } + else + { + if(m_aBuffer[m_BufferPos] == '\n' || m_aBuffer[m_BufferPos] == '\r') + { + // line found + if(m_aBuffer[m_BufferPos] == '\r') + { + if(m_BufferPos + 1 >= m_BufferSize) + { + // read more to get the connected '\n' + CRLFBreak = true; + ++m_BufferPos; + continue; + } + else if(m_aBuffer[m_BufferPos + 1] == '\n') + m_aBuffer[m_BufferPos++] = 0; + } + m_aBuffer[m_BufferPos++] = 0; + return &m_aBuffer[LineStart]; + } + else if(CRLFBreak) + { + if(m_aBuffer[m_BufferPos] == '\n') + m_aBuffer[m_BufferPos++] = 0; + return &m_aBuffer[LineStart]; + } + else + m_BufferPos++; + } + } +} diff --git a/src/engine/shared/linereader.h b/src/engine/shared/linereader.h new file mode 100644 index 000000000..3e1f2ba3a --- /dev/null +++ b/src/engine/shared/linereader.h @@ -0,0 +1,20 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_LINEREADER_H +#define ENGINE_SHARED_LINEREADER_H +#include + +// buffered stream for reading lines, should perhaps be something smaller +class CLineReader +{ + char m_aBuffer[4 * 1024 + 1]; // 1 additional byte for null termination + unsigned m_BufferPos; + unsigned m_BufferSize; + unsigned m_BufferMaxSize; + IOHANDLE m_IO; + +public: + void Init(IOHANDLE IoHandle); + const char *Get(); +}; +#endif diff --git a/src/engine/shared/map.cpp b/src/engine/shared/map.cpp new file mode 100644 index 000000000..66a939fb8 --- /dev/null +++ b/src/engine/shared/map.cpp @@ -0,0 +1,110 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include +#include +#include "datafile.h" + +class CMap : public IEngineMap +{ + CDataFileReader m_DataFile; +public: + CMap() {} + + virtual void *GetData(int Index) { return m_DataFile.GetData(Index); } + virtual void *GetDataSwapped(int Index) { return m_DataFile.GetDataSwapped(Index); } + virtual void UnloadData(int Index) { m_DataFile.UnloadData(Index); } + virtual void *GetItem(int Index, int *pType, int *pID) { return m_DataFile.GetItem(Index, pType, pID); } + virtual void GetType(int Type, int *pStart, int *pNum) { m_DataFile.GetType(Type, pStart, pNum); } + virtual void *FindItem(int Type, int ID) { return m_DataFile.FindItem(Type, ID); } + virtual int NumItems() { return m_DataFile.NumItems(); } + + virtual void Unload() + { + m_DataFile.Close(); + } + + virtual bool Load(const char *pMapName, IStorage *pStorage) + { + if(!pStorage) + pStorage = Kernel()->RequestInterface(); + if(!pStorage) + return false; + if(!m_DataFile.Open(pStorage, pMapName, IStorage::TYPE_ALL)) + return false; + // check version + CMapItemVersion *pItem = (CMapItemVersion *)m_DataFile.FindItem(MAPITEMTYPE_VERSION, 0); + if(!pItem || pItem->m_Version != CMapItemVersion::CURRENT_VERSION) + return false; + + // replace compressed tile layers with uncompressed ones + int GroupsStart, GroupsNum, LayersStart, LayersNum; + m_DataFile.GetType(MAPITEMTYPE_GROUP, &GroupsStart, &GroupsNum); + m_DataFile.GetType(MAPITEMTYPE_LAYER, &LayersStart, &LayersNum); + for(int g = 0; g < GroupsNum; g++) + { + CMapItemGroup *pGroup = static_cast(m_DataFile.GetItem(GroupsStart + g, 0, 0)); + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = static_cast(m_DataFile.GetItem(LayersStart + pGroup->m_StartLayer + l, 0, 0)); + + if(pLayer->m_Type == LAYERTYPE_TILES) + { + CMapItemLayerTilemap *pTilemap = reinterpret_cast(pLayer); + + if(pTilemap->m_Version > 3) + { + const int TilemapCount = pTilemap->m_Width * pTilemap->m_Height; + const int TilemapSize = TilemapCount * sizeof(CTile); + + if((TilemapCount / pTilemap->m_Width != pTilemap->m_Height) || (TilemapSize / (int)sizeof(CTile) != TilemapCount)) + { + dbg_msg("engine", "map layer too big (%d * %d * %u causes an integer overflow)", pTilemap->m_Width, pTilemap->m_Height, unsigned(sizeof(CTile))); + return false; + } + CTile *pTiles = static_cast(mem_alloc(TilemapSize)); + if(!pTiles) + return false; + + // extract original tile data + int i = 0; + CTile *pSavedTiles = static_cast(m_DataFile.GetData(pTilemap->m_Data)); + while(i < TilemapCount) + { + for(unsigned Counter = 0; Counter <= pSavedTiles->m_Skip && i < TilemapCount; Counter++) + { + pTiles[i] = *pSavedTiles; + pTiles[i++].m_Skip = 0; + } + + pSavedTiles++; + } + + m_DataFile.ReplaceData(pTilemap->m_Data, reinterpret_cast(pTiles), TilemapSize); + } + } + } + + } + + return true; + } + + virtual bool IsLoaded() + { + return m_DataFile.IsOpen(); + } + + virtual SHA256_DIGEST Sha256() + { + return m_DataFile.Sha256(); + } + + virtual unsigned Crc() + { + return m_DataFile.Crc(); + } +}; + +extern IEngineMap *CreateEngineMap() { return new CMap; } diff --git a/src/engine/shared/mapchecker.cpp b/src/engine/shared/mapchecker.cpp new file mode 100644 index 000000000..04142371e --- /dev/null +++ b/src/engine/shared/mapchecker.cpp @@ -0,0 +1,132 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include + +#include +#include + +#include "mapchecker.h" + +CMapChecker::CMapChecker() +{ + Init(); + SetDefaults(); +} + +void CMapChecker::Init() +{ + m_Whitelist.Reset(); + m_pFirst = 0; + m_ClearListBeforeAdding = false; +} + +void CMapChecker::SetDefaults() +{ + AddMaplist(s_aMapVersionList, s_NumMapVersionItems); + m_ClearListBeforeAdding = true; +} + +void CMapChecker::AddMaplist(const CMapVersion *pMaplist, int Num) +{ + if(m_ClearListBeforeAdding) + Init(); + + for(int i = 0; i < Num; ++i) + { + CWhitelistEntry *pEntry = (CWhitelistEntry *)m_Whitelist.Allocate(sizeof(CWhitelistEntry)); + pEntry->m_pNext = m_pFirst; + m_pFirst = pEntry; + + str_copy(pEntry->m_aMapName, pMaplist[i].m_aName, sizeof(pEntry->m_aMapName)); + pEntry->m_MapCrc = bytes_be_to_uint(pMaplist[i].m_aCrc); + pEntry->m_MapSize = bytes_be_to_uint(pMaplist[i].m_aSize); + mem_copy(&pEntry->m_MapSha256, &pMaplist[i].m_aSha256, sizeof(pEntry->m_MapSha256)); + } +} + +bool CMapChecker::IsMapValid(const char *pMapName, const SHA256_DIGEST *pMapSha256, unsigned MapCrc, unsigned MapSize) +{ + bool StandardMap = false; + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + { + if(str_comp(pCurrent->m_aMapName, pMapName) == 0) + { + StandardMap = true; + if(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize) + return true; + } + } + return !StandardMap; +} + +bool CMapChecker::ReadAndValidateMap(const char *pFilename, int StorageType) +{ + IStorage *pStorage = Kernel()->RequestInterface(); + + // extract map name + char aMapName[MAX_MAP_LENGTH]; + char aMapNameExt[MAX_MAP_LENGTH+4]; + bool StandardMap = false; + const char *pExtractedName = pFilename; + const char *pEnd = 0; + + for(const char *pSrc = pFilename; *pSrc; ++pSrc) + { + if(*pSrc == '/' || *pSrc == '\\') + pExtractedName = pSrc+1; + else if(*pSrc == '.') + pEnd = pSrc; + } + + int Length = (int)(pEnd - pExtractedName); + if(Length <= 0 || Length >= MAX_MAP_LENGTH) + return true; + str_truncate(aMapName, MAX_MAP_LENGTH, pExtractedName, pEnd - pExtractedName); + str_format(aMapNameExt, sizeof(aMapNameExt), "%s.map", aMapName); + + // check for valid map + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + { + if(str_comp(pCurrent->m_aMapName, aMapName) == 0) + { + StandardMap = true; + char aBuffer[IO_MAX_PATH_LENGTH]; + if(pStorage->FindFile(aMapNameExt, "maps", StorageType, aBuffer, sizeof(aBuffer), &pCurrent->m_MapSha256, pCurrent->m_MapCrc, pCurrent->m_MapSize)) + return true; + } + else if(StandardMap) + break; + } + + return !StandardMap; +} + +int CMapChecker::NumStandardMaps() +{ + int Count = 0; + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + Count++; + return Count; +} + +const char *CMapChecker::GetStandardMapName(int Index) +{ + int i = 0; + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext, i++) + if(i == Index) + return pCurrent->m_aMapName; + return 0x0; +} + +bool CMapChecker::IsStandardMap(const char *pMapName) +{ + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + if(str_comp(pCurrent->m_aMapName, pMapName) == 0) + return true; + return false; +} + +IMapChecker *CreateMapChecker() { return new CMapChecker; } diff --git a/src/engine/shared/mapchecker.h b/src/engine/shared/mapchecker.h new file mode 100644 index 000000000..0f0f7786b --- /dev/null +++ b/src/engine/shared/mapchecker.h @@ -0,0 +1,45 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_MAPCHECKER_H +#define ENGINE_SHARED_MAPCHECKER_H + +#include + +#include "memheap.h" + +class CMapChecker : public IMapChecker +{ + enum + { + MAX_MAP_LENGTH = 8, + }; + + struct CWhitelistEntry + { + char m_aMapName[MAX_MAP_LENGTH]; + SHA256_DIGEST m_MapSha256; + unsigned m_MapCrc; + unsigned m_MapSize; + CWhitelistEntry *m_pNext; + }; + + class CHeap m_Whitelist; + CWhitelistEntry *m_pFirst; + + bool m_ClearListBeforeAdding; // whether to clear the existing list before adding a new map list + + void Init(); + void SetDefaults(); + +public: + CMapChecker(); + void AddMaplist(const struct CMapVersion *pMaplist, int Num); + bool IsMapValid(const char *pMapName, const SHA256_DIGEST *pMapSha256, unsigned MapCrc, unsigned MapSize); + bool ReadAndValidateMap(const char *pFilename, int StorageType); + + int NumStandardMaps(); + const char *GetStandardMapName(int Index); + bool IsStandardMap(const char *pMapName); +}; + +#endif diff --git a/src/engine/shared/masterserver.cpp b/src/engine/shared/masterserver.cpp new file mode 100644 index 000000000..ddda56d6e --- /dev/null +++ b/src/engine/shared/masterserver.cpp @@ -0,0 +1,211 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include // sscanf + +#include + +#include +#include +#include + +#include + +#include "linereader.h" + +class CMasterServer : public IEngineMasterServer +{ +public: + // master server functions + struct CMasterInfo + { + char m_aHostname[128]; + NETADDR m_Addr; + bool m_Valid; + + CHostLookup m_Lookup; + }; + + enum + { + STATE_INIT, + STATE_UPDATE, + STATE_READY, + }; + + CMasterInfo m_aMasterServers[MAX_MASTERSERVERS]; + int m_State; + IEngine *m_pEngine; + IStorage *m_pStorage; + + CMasterServer() + { + SetDefault(); + m_State = STATE_INIT; + m_pEngine = 0; + m_pStorage = 0; + } + + virtual int RefreshAddresses(int Nettype) + { + if(m_State != STATE_INIT && m_State != STATE_READY) + return -1; + + dbg_msg("engine/mastersrv", "refreshing master server addresses"); + + // add lookup jobs + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + m_pEngine->HostLookup(&m_aMasterServers[i].m_Lookup, m_aMasterServers[i].m_aHostname, Nettype); + m_aMasterServers[i].m_Valid = false; + } + + m_State = STATE_UPDATE; + return 0; + } + + virtual void Update() + { + // check if we need to update + if(m_State != STATE_UPDATE) + return; + m_State = STATE_READY; + + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + if(m_aMasterServers[i].m_Lookup.m_Job.Status() != CJob::STATE_DONE) + m_State = STATE_UPDATE; + else + { + if(m_aMasterServers[i].m_Lookup.m_Job.Result() == 0) + { + m_aMasterServers[i].m_Addr = m_aMasterServers[i].m_Lookup.m_Addr; + m_aMasterServers[i].m_Addr.port = MASTERSERVER_PORT; + m_aMasterServers[i].m_Valid = true; + } + else + m_aMasterServers[i].m_Valid = false; + } + } + + if(m_State == STATE_READY) + { + dbg_msg("engine/mastersrv", "saving addresses"); + Save(); + } + } + + virtual bool IsRefreshing() const + { + return m_State != STATE_READY; + } + + virtual NETADDR GetAddr(int Index) const + { + return m_aMasterServers[Index].m_Addr; + } + + virtual const char *GetName(int Index) const + { + return m_aMasterServers[Index].m_aHostname; + } + + virtual bool IsValid(int Index) const + { + return m_aMasterServers[Index].m_Valid; + } + + virtual void Init() + { + m_pEngine = Kernel()->RequestInterface(); + m_pStorage = Kernel()->RequestInterface(); + } + + virtual void SetDefault() + { + mem_zero(m_aMasterServers, sizeof(m_aMasterServers)); + for(int i = 0; i < MAX_MASTERSERVERS; i++) + str_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), "master%d.teeworlds.com", i+1); + } + + virtual int Load() + { + if(!m_pStorage) + return -1; + + // try to open file + IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_READ | IOFLAG_SKIP_BOM, IStorage::TYPE_SAVE); + if(!File) + return -1; + + CLineReader LineReader; + LineReader.Init(File); + while(1) + { + CMasterInfo Info = {{0}}; + const char *pLine = LineReader.Get(); + if(!pLine) + break; + + // parse line + char aAddrStr[NETADDR_MAXSTRSIZE]; + if(sscanf(pLine, "%127s %47s", Info.m_aHostname, aAddrStr) == 2 && net_addr_from_str(&Info.m_Addr, aAddrStr) == 0) + { + Info.m_Addr.port = MASTERSERVER_PORT; + bool Added = false; + for(int i = 0; i < MAX_MASTERSERVERS; ++i) + if(str_comp(m_aMasterServers[i].m_aHostname, Info.m_aHostname) == 0) + { + m_aMasterServers[i] = Info; + Added = true; + break; + } + + if(!Added) + { + for(int i = 0; i < MAX_MASTERSERVERS; ++i) + if(m_aMasterServers[i].m_Addr.type == NETTYPE_INVALID) + { + m_aMasterServers[i] = Info; + Added = true; + break; + } + } + + if(!Added) + break; + } + } + + io_close(File); + return 0; + } + + virtual int Save() + { + if(!m_pStorage) + return -1; + + // try to open file + IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!File) + return -1; + + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + if(m_aMasterServers[i].m_Addr.type != NETTYPE_INVALID) + net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr), true); + else + aAddrStr[0] = 0; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s %s", m_aMasterServers[i].m_aHostname, aAddrStr); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + + io_close(File); + return 0; + } +}; + +IEngineMasterServer *CreateEngineMasterServer() { return new CMasterServer; } diff --git a/src/engine/shared/memheap.cpp b/src/engine/shared/memheap.cpp new file mode 100644 index 000000000..d98918d73 --- /dev/null +++ b/src/engine/shared/memheap.cpp @@ -0,0 +1,95 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include "memheap.h" + + +// allocates a new chunk to be used +void CHeap::NewChunk() +{ + // allocate memory + char *pMem = (char*)mem_alloc(sizeof(CChunk)+CHUNK_SIZE); + if(!pMem) + return; + + // the chunk structure is located in the begining of the chunk + // init it and return the chunk + CChunk *pChunk = (CChunk*)pMem; + pChunk->m_pMemory = (char*)(pChunk+1); + pChunk->m_pCurrent = pChunk->m_pMemory; + pChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE; + pChunk->m_pNext = m_pCurrent; + + m_pCurrent = pChunk; +} + +//**************** +void *CHeap::AllocateFromChunk(unsigned int Size) +{ + // check if we need can fit the allocation + if(m_pCurrent->m_pCurrent + Size > m_pCurrent->m_pEnd) + return (void*)0x0; + + // get memory and move the pointer forward + char *pMem = m_pCurrent->m_pCurrent; + m_pCurrent->m_pCurrent += Size; + return pMem; +} + +// creates a heap +CHeap::CHeap() +{ + m_pCurrent = 0x0; + NewChunk(); +} + +CHeap::~CHeap() +{ + Clear(); +} + +void CHeap::Reset() +{ + Clear(); + NewChunk(); +} + +// destroys the heap +void CHeap::Clear() +{ + CChunk *pChunk = m_pCurrent; + + while(pChunk) + { + CChunk *pNext = pChunk->m_pNext; + mem_free(pChunk); + pChunk = pNext; + } + + m_pCurrent = 0x0; +} + +// +void *CHeap::Allocate(unsigned int Size) +{ + // try to allocate from current chunk + char *pMem = (char *)AllocateFromChunk(Size); + if(!pMem) + { + // allocate new chunk and add it to the heap + NewChunk(); + + // try to allocate again + pMem = (char *)AllocateFromChunk(Size); + } + + return pMem; +} + +const char *CHeap::StoreString(const char *pSrc) +{ + const int Size = str_length(pSrc) + 1; + char *pMem = static_cast(Allocate(Size)); + str_copy(pMem, pSrc, Size); + return pMem; +} diff --git a/src/engine/shared/memheap.h b/src/engine/shared/memheap.h new file mode 100644 index 000000000..a455dce2e --- /dev/null +++ b/src/engine/shared/memheap.h @@ -0,0 +1,35 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_MEMHEAP_H +#define ENGINE_SHARED_MEMHEAP_H +class CHeap +{ + struct CChunk + { + char *m_pMemory; + char *m_pCurrent; + char *m_pEnd; + CChunk *m_pNext; + }; + + enum + { + // how large each chunk should be + CHUNK_SIZE = 1024*64, + }; + + CChunk *m_pCurrent; + + + void Clear(); + void NewChunk(); + void *AllocateFromChunk(unsigned int Size); + +public: + CHeap(); + ~CHeap(); + void Reset(); + void *Allocate(unsigned int Size); + const char *StoreString(const char *pSrc); +}; +#endif diff --git a/src/engine/shared/netban.cpp b/src/engine/shared/netban.cpp new file mode 100644 index 000000000..92f797914 --- /dev/null +++ b/src/engine/shared/netban.cpp @@ -0,0 +1,627 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include + +#include "netban.h" + + +CNetBan::CNetHash::CNetHash(const NETADDR *pAddr) +{ + if(pAddr->type==NETTYPE_IPV4) + m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF; + else + m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+ + pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF; + m_HashIndex = 0; +} + +CNetBan::CNetHash::CNetHash(const CNetRange *pRange) +{ + m_Hash = 0; + m_HashIndex = 0; + for(int i = 0; pRange->m_LB.ip[i] == pRange->m_UB.ip[i]; ++i) + { + m_Hash += pRange->m_LB.ip[i]; + ++m_HashIndex; + } + m_Hash &= 0xFF; +} + +int CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]) +{ + int Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16; + aHash[0].m_Hash = 0; + aHash[0].m_HashIndex = 0; + for(int i = 1, Sum = 0; i <= Length; ++i) + { + Sum += pAddr->ip[i-1]; + aHash[i].m_Hash = Sum&0xFF; + aHash[i].m_HashIndex = i%Length; + } + return Length; +} + + +template +typename CNetBan::CBan *CNetBan::CBanPool::Add(const T *pData, const CBanInfo *pInfo, const CNetHash *pNetHash) +{ + if(!m_pFirstFree) + return 0; + + // create new ban + CBan *pBan = m_pFirstFree; + pBan->m_Data = *pData; + pBan->m_Info = *pInfo; + pBan->m_NetHash = *pNetHash; + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstFree = pBan->m_pNext; + + // add it to the hash list + if(m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]) + m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]->m_pHashPrev = pBan; + pBan->m_pHashPrev = 0; + pBan->m_pHashNext = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; + m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash] = pBan; + + // insert it into the used list + if(m_pFirstUsed) + { + for(CBan *p = m_pFirstUsed; ; p = p->m_pNext) + { + if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) + { + // insert before + pBan->m_pNext = p; + pBan->m_pPrev = p->m_pPrev; + if(p->m_pPrev) + p->m_pPrev->m_pNext = pBan; + else + m_pFirstUsed = pBan; + p->m_pPrev = pBan; + break; + } + + if(!p->m_pNext) + { + // last entry + p->m_pNext = pBan; + pBan->m_pPrev = p; + pBan->m_pNext = 0; + break; + } + } + } + else + { + m_pFirstUsed = pBan; + pBan->m_pNext = pBan->m_pPrev = 0; + } + + // update ban count + ++m_CountUsed; + + return pBan; +} + +template +int CNetBan::CBanPool::Remove(CBan *pBan) +{ + if(pBan == 0) + return -1; + + // remove from hash list + if(pBan->m_pHashNext) + pBan->m_pHashNext->m_pHashPrev = pBan->m_pHashPrev; + if(pBan->m_pHashPrev) + pBan->m_pHashPrev->m_pHashNext = pBan->m_pHashNext; + else + m_paaHashList[pBan->m_NetHash.m_HashIndex][pBan->m_NetHash.m_Hash] = pBan->m_pHashNext; + pBan->m_pHashNext = pBan->m_pHashPrev = 0; + + // remove from used list + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstUsed = pBan->m_pNext; + + // add to recycle list + if(m_pFirstFree) + m_pFirstFree->m_pPrev = pBan; + pBan->m_pPrev = 0; + pBan->m_pNext = m_pFirstFree; + m_pFirstFree = pBan; + + // update ban count + --m_CountUsed; + + return 0; +} + +template +void CNetBan::CBanPool::Update(CBan *pBan, const CBanInfo *pInfo) +{ + pBan->m_Info = *pInfo; + + // remove from used list + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstUsed = pBan->m_pNext; + + // insert it into the used list + if(m_pFirstUsed) + { + for(CBan *p = m_pFirstUsed; ; p = p->m_pNext) + { + if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) + { + // insert before + pBan->m_pNext = p; + pBan->m_pPrev = p->m_pPrev; + if(p->m_pPrev) + p->m_pPrev->m_pNext = pBan; + else + m_pFirstUsed = pBan; + p->m_pPrev = pBan; + break; + } + + if(!p->m_pNext) + { + // last entry + p->m_pNext = pBan; + pBan->m_pPrev = p; + pBan->m_pNext = 0; + break; + } + } + } + else + { + m_pFirstUsed = pBan; + pBan->m_pNext = pBan->m_pPrev = 0; + } +} + +template +void CNetBan::CBanPool::Reset() +{ + mem_zero(m_paaHashList, sizeof(m_paaHashList)); + mem_zero(m_aBans, sizeof(m_aBans)); + m_pFirstUsed = 0; + m_CountUsed = 0; + + for(int i = 1; i < MAX_BANS-1; ++i) + { + m_aBans[i].m_pNext = &m_aBans[i+1]; + m_aBans[i].m_pPrev = &m_aBans[i-1]; + } + + m_aBans[0].m_pNext = &m_aBans[1]; + m_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2]; + m_pFirstFree = &m_aBans[0]; +} + +template +typename CNetBan::CBan *CNetBan::CBanPool::Get(int Index) const +{ + if(Index < 0 || Index >= Num()) + return 0; + + for(CNetBan::CBan *pBan = m_pFirstUsed; pBan; pBan = pBan->m_pNext, --Index) + { + if(Index == 0) + return pBan; + } + + return 0; +} + + +template +void CNetBan::MakeBanInfo(CBan *pBan, char *pBuf, unsigned BuffSize, int Type, int *pLastInfoQuery) +{ + if(pBan == 0 || pBuf == 0) + { + if(BuffSize > 0) + pBuf[0] = 0; + return; + } + + // build type based part + char aBuf[256]; + if(Type == MSGTYPE_PLAYER) + str_copy(aBuf, "You have been banned", sizeof(aBuf)); + else + { + char aTemp[256]; + switch(Type) + { + case MSGTYPE_LIST: + str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + case MSGTYPE_BANADD: + str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + case MSGTYPE_BANREM: + str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + default: + aBuf[0] = 0; + } + } + + // add info part + int Time = time_timestamp(); + if(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER) + { + int Mins = ((pBan->m_Info.m_Expires-Time) + 59) / 60; + if(Mins <= 1) + str_format(pBuf, BuffSize, "%s for 1 minute (%s)", aBuf, pBan->m_Info.m_aReason); + else + str_format(pBuf, BuffSize, "%s for %d minutes (%s)", aBuf, Mins, pBan->m_Info.m_aReason); + } + else + str_format(pBuf, BuffSize, "%s for life (%s)", aBuf, pBan->m_Info.m_aReason); + + if(pLastInfoQuery) + { + *pLastInfoQuery = pBan->m_Info.m_LastInfoQuery; + pBan->m_Info.m_LastInfoQuery = Time; + } +} + +template +int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) +{ + // do not ban localhost + if(!IsBannable(pData)) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (localhost)"); + return -1; + } + + int Time = time_timestamp(); + int Stamp = Seconds > 0 ? Time+Seconds : CBanInfo::EXPIRES_NEVER; + + // set up info + CBanInfo Info = {0}; + Info.m_Expires = Stamp; + Info.m_LastInfoQuery = Time; + str_copy(Info.m_aReason, pReason, sizeof(Info.m_aReason)); + + // check if it already exists + CNetHash NetHash(pData); + CBan *pBan = pBanPool->Find(pData, &NetHash); + if(pBan) + { + // adjust the ban + pBanPool->Update(pBan, &Info); + char aBuf[128]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 1; + } + + // add ban and print result + pBan = pBanPool->Add(pData, &Info, &NetHash); + if(pBan) + { + char aBuf[128]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANADD); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 0; + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (full banlist)"); + return -1; +} + +template +int CNetBan::Unban(T *pBanPool, const typename T::CDataType *pData) +{ + CNetHash NetHash(pData); + CBan *pBan = pBanPool->Find(pData, &NetHash); + if(pBan) + { + char aBuf[256]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANREM); + pBanPool->Remove(pBan); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 0; + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid entry)"); + return -1; +} + +void CNetBan::Init(IConsole *pConsole, IStorage *pStorage) +{ + m_pConsole = pConsole; + m_pStorage = pStorage; + m_BanAddrPool.Reset(); + m_BanRangePool.Reset(); + + net_host_lookup("localhost", &m_LocalhostIPV4, NETTYPE_IPV4); + net_host_lookup("localhost", &m_LocalhostIPV6, NETTYPE_IPV6); + + Console()->Register("ban", "s[ip|range] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, "Ban IP (or IP range) for x minutes for any reason"); + Console()->Register("unban", "s[ip|range]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, "Unban IP/IP range/banlist entry"); + Console()->Register("unban_all", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries"); + Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, "Show banlist"); + Console()->Register("bans_save", "s[file]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file"); +} + +void CNetBan::Update() +{ + int Now = time_timestamp(); + + // remove expired bans + char aBuf[256], aNetStr[256]; + while(m_BanAddrPool.First() && m_BanAddrPool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanAddrPool.First()->m_Info.m_Expires < Now) + { + str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanAddrPool.First()->m_Data, aNetStr, sizeof(aNetStr))); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + m_BanAddrPool.Remove(m_BanAddrPool.First()); + } + while(m_BanRangePool.First() && m_BanRangePool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanRangePool.First()->m_Info.m_Expires < Now) + { + str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanRangePool.First()->m_Data, aNetStr, sizeof(aNetStr))); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + m_BanRangePool.Remove(m_BanRangePool.First()); + } +} + +int CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) +{ + return Ban(&m_BanAddrPool, pAddr, Seconds, pReason); +} + +int CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) +{ + if(pRange->IsValid()) + return Ban(&m_BanRangePool, pRange, Seconds, pReason); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +int CNetBan::UnbanByAddr(const NETADDR *pAddr) +{ + return Unban(&m_BanAddrPool, pAddr); +} + +int CNetBan::UnbanByRange(const CNetRange *pRange) +{ + if(pRange->IsValid()) + return Unban(&m_BanRangePool, pRange); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +int CNetBan::UnbanByIndex(int Index) +{ + int Result; + char aBuf[256]; + CBanAddr *pBan = m_BanAddrPool.Get(Index); + if(pBan) + { + NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); + Result = m_BanAddrPool.Remove(pBan); + } + else + { + CBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num()); + if(pBan) + { + NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); + Result = m_BanRangePool.Remove(pBan); + } + else + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid index)"); + return -1; + } + } + + char aMsg[256]; + str_format(aMsg, sizeof(aMsg), "unbanned index %i (%s)", Index, aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + return Result; +} + +void CNetBan::UnbanAll() +{ + m_BanAddrPool.Reset(); + m_BanRangePool.Reset(); +} + +template +bool CNetBan::IsBannable(const T *pData) +{ + // do not ban localhost + if(NetMatch(pData, &m_LocalhostIPV4) || NetMatch(pData, &m_LocalhostIPV6)) + { + return false; + } + return true; +} + +bool CNetBan::IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize, int *pLastInfoQuery) +{ + CNetHash aHash[17]; + int Length = CNetHash::MakeHashArray(pAddr, aHash); + + // check ban addresses + CBanAddr *pBan = m_BanAddrPool.Find(pAddr, &aHash[Length]); + if(pBan) + { + MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER, pLastInfoQuery); + return true; + } + + // check ban ranges + for(int i = Length-1; i >= 0; --i) + { + for(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext) + { + if(NetMatch(&pBan->m_Data, pAddr, i, Length)) + { + MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER, pLastInfoQuery); + return true; + } + } + } + + return false; +} + +void CNetBan::ConBan(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast(pUser); + + char aBuf[256]; + str_copy(aBuf, pResult->GetString(0), sizeof(aBuf)); + const char *pSeparator = str_find(aBuf, "-"); + + const int Minutes = pResult->NumArguments() > 1 ? clamp(pResult->GetInteger(1), 0, 31*24*60) : 30; + const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(2) : "No reason given"; + + if(pSeparator == NULL || pSeparator[1] == '\0') + { + NETADDR Addr; + if(net_addr_from_str(&Addr, aBuf) == 0) + pThis->BanAddr(&Addr, Minutes*60, pReason); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid network address)"); + } + else + { + aBuf[pSeparator-&aBuf[0]] = '\0'; + + CNetRange Range; + if(net_addr_from_str(&Range.m_LB, aBuf) == 0 && net_addr_from_str(&Range.m_UB, pSeparator+1) == 0) + pThis->BanRange(&Range, Minutes*60, pReason); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid range)"); + } +} + +void CNetBan::ConUnban(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast(pUser); + + char aBuf[256]; + str_copy(aBuf, pResult->GetString(0), sizeof(aBuf)); + const char *pSeparator = str_find(aBuf, "-"); + + if(!str_is_number(aBuf)) + { + pThis->UnbanByIndex(str_toint(aBuf)); + } + else if(pSeparator == NULL || pSeparator[1] == '\0') + { + NETADDR Addr; + if(net_addr_from_str(&Addr, aBuf) == 0) + pThis->UnbanByAddr(&Addr); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid network address)"); + } + else + { + aBuf[pSeparator-&aBuf[0]] = '\0'; + + CNetRange Range; + if(net_addr_from_str(&Range.m_LB, aBuf) == 0 && net_addr_from_str(&Range.m_UB, pSeparator+1) == 0) + pThis->UnbanByRange(&Range); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid range)"); + } +} + +void CNetBan::ConUnbanAll(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast(pUser); + + pThis->UnbanAll(); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unbanned all entries"); +} + +void CNetBan::ConBans(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast(pUser); + + int Count = 0; + char aBuf[256], aMsg[256]; + for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) + { + pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + } + for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) + { + pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + } + str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count==1?"ban":"bans"); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); +} + +void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast(pUser); + char aBuf[256]; + const char *pFilename = pResult->GetString(0); + + IOHANDLE File = pThis->Storage()->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!File) + { + str_format(aBuf, sizeof(aBuf), "failed to save banlist to '%s'", pFilename); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return; + } + + int Now = time_timestamp(); + char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; + for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) + { + int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + net_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false); + str_format(aBuf, sizeof(aBuf), "ban %s %i %s", aAddrStr1, Min, pBan->m_Info.m_aReason); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) + { + int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + net_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false); + net_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false); + str_format(aBuf, sizeof(aBuf), "ban %s-%s %i %s", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + + io_close(File); + str_format(aBuf, sizeof(aBuf), "saved banlist to '%s'", pFilename); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); +} + +// explicitly instantiate template for src/engine/server/server.cpp +template void CNetBan::MakeBanInfo(CBan *pBan, char *pBuf, unsigned BufferSize, int Type, int *pLastInfoQuery); +template void CNetBan::MakeBanInfo(CBan *pBan, char *pBuf, unsigned BufferSize, int Type, int *pLastInfoQuery); +template int CNetBan::Ban >(CNetBan::CBanPool *pBanPool, const NETADDR *pData, int Seconds, const char *pReason); +template int CNetBan::Ban >(CNetBan::CBanPool *pBanPool, const CNetRange *pData, int Seconds, const char *pReason); +template bool CNetBan::IsBannable(const NETADDR *pData); +template bool CNetBan::IsBannable(const CNetRange *pData); diff --git a/src/engine/shared/netban.h b/src/engine/shared/netban.h new file mode 100644 index 000000000..015744104 --- /dev/null +++ b/src/engine/shared/netban.h @@ -0,0 +1,192 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_NETBAN_H +#define ENGINE_SHARED_NETBAN_H + +#include + + +inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2) +{ + return net_addr_comp(pAddr1, pAddr2, false); +} + +class CNetRange +{ +public: + NETADDR m_LB; + NETADDR m_UB; + + bool IsValid() const { return m_LB.type == m_UB.type && mem_comp(m_LB.ip, m_UB.ip, m_LB.type==NETTYPE_IPV4 ? NETADDR_SIZE_IPV4 : NETADDR_SIZE_IPV6) < 0; } +}; + +inline int NetComp(const CNetRange *pRange1, const CNetRange *pRange2) +{ + return net_addr_comp(&pRange1->m_LB, &pRange2->m_LB, false) || net_addr_comp(&pRange1->m_UB, &pRange2->m_UB, false); +} + + +class CNetBan +{ +protected: + bool NetMatch(const NETADDR *pAddr1, const NETADDR *pAddr2) const + { + return NetComp(pAddr1, pAddr2) == 0; + } + + bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const + { + return pRange->m_LB.type == pAddr->type && (Start == 0 || mem_comp(&pRange->m_LB.ip[0], &pAddr->ip[0], Start) == 0) && + mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0; + } + + bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const + { + return NetMatch(pRange, pAddr, 0, pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16); + } + + const char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pData, aAddrStr, sizeof(aAddrStr), false); + str_format(pBuffer, BufferSize, "'%s'", aAddrStr); + return pBuffer; + } + + const char *NetToString(const CNetRange *pData, char *pBuffer, unsigned BufferSize) const + { + char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; + net_addr_str(&pData->m_LB, aAddrStr1, sizeof(aAddrStr1), false); + net_addr_str(&pData->m_UB, aAddrStr2, sizeof(aAddrStr2), false); + str_format(pBuffer, BufferSize, "'%s' - '%s'", aAddrStr1, aAddrStr2); + return pBuffer; + } + + class CNetHash + { + public: + int m_Hash; + int m_HashIndex; // matching parts for ranges, 0 for addr + + CNetHash() {} + CNetHash(const NETADDR *pAddr); + CNetHash(const CNetRange *pRange); + + static int MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]); + }; + + struct CBanInfo + { + enum + { + EXPIRES_NEVER=-1, + REASON_LENGTH=64, + }; + int m_Expires; + int m_LastInfoQuery; + char m_aReason[REASON_LENGTH]; + }; + + template struct CBan + { + T m_Data; + CBanInfo m_Info; + CNetHash m_NetHash; + + // hash list + CBan *m_pHashNext; + CBan *m_pHashPrev; + + // used or free list + CBan *m_pNext; + CBan *m_pPrev; + }; + + template class CBanPool + { + public: + typedef T CDataType; + + CBan *Add(const CDataType *pData, const CBanInfo *pInfo, const CNetHash *pNetHash); + int Remove(CBan *pBan); + void Update(CBan *pBan, const CBanInfo *pInfo); + void Reset(); + + int Num() const { return m_CountUsed; } + bool IsFull() const { return m_CountUsed == MAX_BANS; } + + CBan *First() const { return m_pFirstUsed; } + CBan *First(const CNetHash *pNetHash) const { return m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; } + CBan *Find(const CDataType *pData, const CNetHash *pNetHash) const + { + for(CBan *pBan = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; pBan; pBan = pBan->m_pHashNext) + { + if(NetComp(&pBan->m_Data, pData) == 0) + return pBan; + } + + return 0; + } + CBan *Get(int Index) const; + + private: + enum + { + MAX_BANS=1024, + }; + + CBan *m_paaHashList[HashCount][256]; + CBan m_aBans[MAX_BANS]; + CBan *m_pFirstFree; + CBan *m_pFirstUsed; + int m_CountUsed; + }; + + typedef CBanPool CBanAddrPool; + typedef CBanPool CBanRangePool; + typedef CBan CBanAddr; + typedef CBan CBanRange; + + template void MakeBanInfo(CBan *pBan, char *pBuf, unsigned BuffSize, int Type, int *pLastInfoQuery=0); + template int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + template int Unban(T *pBanPool, const typename T::CDataType *pData); + + class IConsole *m_pConsole; + class IStorage *m_pStorage; + CBanAddrPool m_BanAddrPool; + CBanRangePool m_BanRangePool; + NETADDR m_LocalhostIPV4, m_LocalhostIPV6; + +public: + enum + { + MSGTYPE_PLAYER=0, + MSGTYPE_LIST, + MSGTYPE_BANADD, + MSGTYPE_BANREM, + }; + + class IConsole *Console() const { return m_pConsole; } + class IStorage *Storage() const { return m_pStorage; } + + virtual ~CNetBan() {} + void Init(class IConsole *pConsole, class IStorage *pStorage); + void Update(); + + virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); + virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); + int UnbanByAddr(const NETADDR *pAddr); + int UnbanByRange(const CNetRange *pRange); + int UnbanByIndex(int Index); + void UnbanAll(); + template bool IsBannable(const T *pData); + bool IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize, int *pLastInfoQuery); + + static void ConBan(class IConsole::IResult *pResult, void *pUser); + static void ConUnban(class IConsole::IResult *pResult, void *pUser); + static void ConUnbanAll(class IConsole::IResult *pResult, void *pUser); + static void ConBans(class IConsole::IResult *pResult, void *pUser); + static void ConBansSave(class IConsole::IResult *pResult, void *pUser); +}; + +#endif diff --git a/src/engine/shared/network.cpp b/src/engine/shared/network.cpp new file mode 100644 index 000000000..d945ccba7 --- /dev/null +++ b/src/engine/shared/network.cpp @@ -0,0 +1,413 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include + +#include "config.h" +#include "console.h" +#include "network.h" +#include "huffman.h" + + +static void ConchainDbgLognetwork(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + ((CNetBase *)pUserData)->UpdateLogHandles(); +} + +void CNetRecvUnpacker::Clear() +{ + m_Valid = false; +} + +void CNetRecvUnpacker::Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID) +{ + m_Addr = *pAddr; + m_pConnection = pConnection; + m_ClientID = ClientID; + m_CurrentChunk = 0; + m_Valid = true; +} + +// TODO: rename this function +int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) +{ + // Don't bother with connections that already went offline + if(m_pConnection && m_pConnection->State() != NET_CONNSTATE_ONLINE) + { + Clear(); + return 0; + } + + CNetChunkHeader Header; + unsigned char *pEnd = m_Data.m_aChunkData + m_Data.m_DataSize; + + while(1) + { + unsigned char *pData = m_Data.m_aChunkData; + + // check for old data to unpack + if(!m_Valid || m_CurrentChunk >= m_Data.m_NumChunks) + { + Clear(); + return 0; + } + + // TODO: add checking here so we don't read too far + for(int i = 0; i < m_CurrentChunk; i++) + { + pData = Header.Unpack(pData); + pData += Header.m_Size; + } + + // unpack the header + pData = Header.Unpack(pData); + m_CurrentChunk++; + + if(pData+Header.m_Size > pEnd) + { + Clear(); + return 0; + } + + // handle sequence stuff + if(m_pConnection && (Header.m_Flags&NET_CHUNKFLAG_VITAL)) + { + if(Header.m_Sequence == (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE) + { + // in sequence + m_pConnection->m_Ack = (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE; + } + else + { + // old packet that we already got + if(m_pConnection->IsSeqInBackroom(Header.m_Sequence, m_pConnection->m_Ack)) + continue; + + // out of sequence, request resend + if(m_pConnection->Config()->m_Debug) + dbg_msg("conn", "asking for resend %d %d", Header.m_Sequence, (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE); + m_pConnection->SignalResend(); + continue; // take the next chunk in the packet + } + } + + // fill in the info + pChunk->m_ClientID = m_ClientID; + pChunk->m_Address = m_Addr; + pChunk->m_Flags = (Header.m_Flags&NET_CHUNKFLAG_VITAL) ? NETSENDFLAG_VITAL : 0; + pChunk->m_DataSize = Header.m_Size; + pChunk->m_pData = pData; + return 1; + } +} +CNetBase::CNetInitializer CNetBase::m_NetInitializer; + +CNetBase::CNetBase() +{ + net_invalidate_socket(&m_Socket); + m_pConfig = 0; + m_pEngine = 0; + m_DataLogSent = 0; + m_DataLogRecv = 0; +} + +CNetBase::~CNetBase() +{ + if(m_Socket.type != NETTYPE_INVALID) + Shutdown(); +} + +void CNetBase::Init(NETSOCKET Socket, CConfig *pConfig, IConsole *pConsole, IEngine *pEngine) +{ + m_Socket = Socket; + m_pConfig = pConfig; + m_pEngine = pEngine; + m_Huffman.Init(); + mem_zero(m_aRequestTokenBuf, sizeof(m_aRequestTokenBuf)); + if(pEngine) + pConsole->Chain("dbg_lognetwork", ConchainDbgLognetwork, this); +} + +void CNetBase::Shutdown() +{ + net_udp_close(m_Socket); + net_invalidate_socket(&m_Socket); +} + +void CNetBase::Wait(int Time) +{ + net_socket_read_wait(m_Socket, Time); +} + +// packs the data tight and sends it +void CNetBase::SendPacketConnless(const NETADDR *pAddr, TOKEN Token, TOKEN ResponseToken, const void *pData, int DataSize) +{ + unsigned char aBuffer[NET_MAX_PACKETSIZE]; + + dbg_assert(DataSize <= NET_MAX_PAYLOAD, "packet data size too high"); + dbg_assert((Token&~NET_TOKEN_MASK) == 0, "token out of range"); + dbg_assert((ResponseToken&~NET_TOKEN_MASK) == 0, "resp token out of range"); + + int i = 0; + aBuffer[i++] = ((NET_PACKETFLAG_CONNLESS<<2)&0xfc) | (NET_PACKETVERSION&0x03); // connless flag and version + aBuffer[i++] = (Token>>24)&0xff; // token + aBuffer[i++] = (Token>>16)&0xff; + aBuffer[i++] = (Token>>8)&0xff; + aBuffer[i++] = (Token)&0xff; + aBuffer[i++] = (ResponseToken>>24)&0xff; // response token + aBuffer[i++] = (ResponseToken>>16)&0xff; + aBuffer[i++] = (ResponseToken>>8)&0xff; + aBuffer[i++] = (ResponseToken)&0xff; + + dbg_assert(i == NET_PACKETHEADERSIZE_CONNLESS, "inconsistency"); + + mem_copy(&aBuffer[i], pData, DataSize); + net_udp_send(m_Socket, pAddr, aBuffer, i+DataSize); +} + +void CNetBase::SendPacket(const NETADDR *pAddr, CNetPacketConstruct *pPacket) +{ + unsigned char aBuffer[NET_MAX_PACKETSIZE]; + int CompressedSize = -1; + int FinalSize = -1; + + // log the data + if(m_DataLogSent) + { + int Type = 1; + io_write(m_DataLogSent, &Type, sizeof(Type)); + io_write(m_DataLogSent, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); + io_write(m_DataLogSent, &pPacket->m_aChunkData, pPacket->m_DataSize); + io_flush(m_DataLogSent); + } + + dbg_assert((pPacket->m_Token&~NET_TOKEN_MASK) == 0, "token out of range"); + + // compress if not ctrl msg + if(!(pPacket->m_Flags&NET_PACKETFLAG_CONTROL)) + CompressedSize = m_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[NET_PACKETHEADERSIZE], NET_MAX_PAYLOAD); + + // check if the compression was enabled, successful and good enough + if(CompressedSize > 0 && CompressedSize < pPacket->m_DataSize) + { + FinalSize = CompressedSize; + pPacket->m_Flags |= NET_PACKETFLAG_COMPRESSION; + } + else + { + // use uncompressed data + FinalSize = pPacket->m_DataSize; + mem_copy(&aBuffer[NET_PACKETHEADERSIZE], pPacket->m_aChunkData, pPacket->m_DataSize); + pPacket->m_Flags &= ~NET_PACKETFLAG_COMPRESSION; + } + + // set header and send the packet if all things are good + if(FinalSize >= 0) + { + FinalSize += NET_PACKETHEADERSIZE; + + int i = 0; + aBuffer[i++] = ((pPacket->m_Flags<<2)&0xfc) | ((pPacket->m_Ack>>8)&0x03); // flags and ack + aBuffer[i++] = (pPacket->m_Ack)&0xff; // ack + aBuffer[i++] = (pPacket->m_NumChunks)&0xff; // num chunks + aBuffer[i++] = (pPacket->m_Token>>24)&0xff; // token + aBuffer[i++] = (pPacket->m_Token>>16)&0xff; + aBuffer[i++] = (pPacket->m_Token>>8)&0xff; + aBuffer[i++] = (pPacket->m_Token)&0xff; + + dbg_assert(i == NET_PACKETHEADERSIZE, "inconsistency"); + + net_udp_send(m_Socket, pAddr, aBuffer, FinalSize); + + // log raw socket data + if(m_DataLogSent) + { + int Type = 0; + io_write(m_DataLogSent, &Type, sizeof(Type)); + io_write(m_DataLogSent, &FinalSize, sizeof(FinalSize)); + io_write(m_DataLogSent, aBuffer, FinalSize); + io_flush(m_DataLogSent); + } + } +} + +// TODO: rename this function +int CNetBase::UnpackPacket(NETADDR *pAddr, unsigned char *pBuffer, CNetPacketConstruct *pPacket) +{ + int Size = net_udp_recv(m_Socket, pAddr, pBuffer, NET_MAX_PACKETSIZE); + // no more packets for now + if(Size <= 0) + return 1; + + // log the data + if(m_DataLogRecv) + { + int Type = 0; + io_write(m_DataLogRecv, &Type, sizeof(Type)); + io_write(m_DataLogRecv, &Size, sizeof(Size)); + io_write(m_DataLogRecv, pBuffer, Size); + io_flush(m_DataLogRecv); + } + + // check the size + if(Size < NET_PACKETHEADERSIZE || Size > NET_MAX_PACKETSIZE) + { + if(m_pConfig->m_Debug) + dbg_msg("network", "packet too small, size=%d", Size); + return -1; + } + + // read the packet + + pPacket->m_Flags = (pBuffer[0]&0xfc)>>2; + // FFFFFFxx + if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) + { + if(Size < NET_PACKETHEADERSIZE_CONNLESS) + { + if(m_pConfig->m_Debug) + dbg_msg("net", "connless packet too small, size=%d", Size); + return -1; + } + + pPacket->m_Flags = NET_PACKETFLAG_CONNLESS; + pPacket->m_Ack = 0; + pPacket->m_NumChunks = 0; + int Version = pBuffer[0]&0x3; + // xxxxxxVV + + if(Version != NET_PACKETVERSION) + return -1; + + pPacket->m_DataSize = Size - NET_PACKETHEADERSIZE_CONNLESS; + pPacket->m_Token = (pBuffer[1] << 24) | (pBuffer[2] << 16) | (pBuffer[3] << 8) | pBuffer[4]; + // TTTTTTTT TTTTTTTT TTTTTTTT TTTTTTTT + pPacket->m_ResponseToken = (pBuffer[5]<<24) | (pBuffer[6]<<16) | (pBuffer[7]<<8) | pBuffer[8]; + // RRRRRRRR RRRRRRRR RRRRRRRR RRRRRRRR + mem_copy(pPacket->m_aChunkData, &pBuffer[NET_PACKETHEADERSIZE_CONNLESS], pPacket->m_DataSize); + } + else + { + if(Size - NET_PACKETHEADERSIZE > NET_MAX_PAYLOAD) + { + if(m_pConfig->m_Debug) + dbg_msg("network", "packet payload too big, size=%d", Size); + return -1; + } + + pPacket->m_Ack = ((pBuffer[0]&0x3)<<8) | pBuffer[1]; + // xxxxxxAA AAAAAAAA + pPacket->m_NumChunks = pBuffer[2]; + // NNNNNNNN + + pPacket->m_DataSize = Size - NET_PACKETHEADERSIZE; + pPacket->m_Token = (pBuffer[3] << 24) | (pBuffer[4] << 16) | (pBuffer[5] << 8) | pBuffer[6]; + // TTTTTTTT TTTTTTTT TTTTTTTT TTTTTTTT + pPacket->m_ResponseToken = NET_TOKEN_NONE; + + if(pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION) + pPacket->m_DataSize = m_Huffman.Decompress(&pBuffer[NET_PACKETHEADERSIZE], pPacket->m_DataSize, pPacket->m_aChunkData, sizeof(pPacket->m_aChunkData)); + else + mem_copy(pPacket->m_aChunkData, &pBuffer[NET_PACKETHEADERSIZE], pPacket->m_DataSize); + } + + // check for errors + if(pPacket->m_DataSize < 0) + { + if(m_pConfig->m_Debug) + dbg_msg("network", "error during packet decoding"); + return -1; + } + + // set the response token (a bit hacky because this function shouldn't know about control packets) + if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) + { + if(pPacket->m_DataSize >= 5) // control byte + token + { + if(pPacket->m_aChunkData[0] == NET_CTRLMSG_CONNECT + || pPacket->m_aChunkData[0] == NET_CTRLMSG_TOKEN) + { + pPacket->m_ResponseToken = (pPacket->m_aChunkData[1]<<24) | (pPacket->m_aChunkData[2]<<16) + | (pPacket->m_aChunkData[3]<<8) | pPacket->m_aChunkData[4]; + } + } + } + + // log the data + if(m_DataLogRecv) + { + int Type = 1; + io_write(m_DataLogRecv, &Type, sizeof(Type)); + io_write(m_DataLogRecv, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); + io_write(m_DataLogRecv, pPacket->m_aChunkData, pPacket->m_DataSize); + io_flush(m_DataLogRecv); + } + + // return success + return 0; +} + + +void CNetBase::SendControlMsg(const NETADDR *pAddr, TOKEN Token, int Ack, int ControlMsg, const void *pExtra, int ExtraSize) +{ + CNetPacketConstruct Construct; + Construct.m_Token = Token; + Construct.m_Flags = NET_PACKETFLAG_CONTROL; + Construct.m_Ack = Ack; + Construct.m_NumChunks = 0; + Construct.m_DataSize = 1+ExtraSize; + Construct.m_aChunkData[0] = ControlMsg; + if(ExtraSize > 0) + mem_copy(&Construct.m_aChunkData[1], pExtra, ExtraSize); + + // send the control message + SendPacket(pAddr, &Construct); +} + + +void CNetBase::SendControlMsgWithToken(const NETADDR *pAddr, TOKEN Token, int Ack, int ControlMsg, TOKEN MyToken, bool Extended) +{ + dbg_assert((Token&~NET_TOKEN_MASK) == 0, "token out of range"); + dbg_assert((MyToken&~NET_TOKEN_MASK) == 0, "resp token out of range"); + + m_aRequestTokenBuf[0] = (MyToken>>24)&0xff; + m_aRequestTokenBuf[1] = (MyToken>>16)&0xff; + m_aRequestTokenBuf[2] = (MyToken>>8)&0xff; + m_aRequestTokenBuf[3] = (MyToken)&0xff; + SendControlMsg(pAddr, Token, 0, ControlMsg, m_aRequestTokenBuf, Extended ? sizeof(m_aRequestTokenBuf) : 4); +} + +unsigned char *CNetChunkHeader::Pack(unsigned char *pData) +{ + pData[0] = ((m_Flags&0x03)<<6) | ((m_Size>>6)&0x3F); + pData[1] = (m_Size&0x3F); + if(m_Flags&NET_CHUNKFLAG_VITAL) + { + pData[1] |= (m_Sequence>>2)&0xC0; + pData[2] = m_Sequence&0xFF; + return pData + 3; + } + return pData + 2; +} + +unsigned char *CNetChunkHeader::Unpack(unsigned char *pData) +{ + m_Flags = (pData[0]>>6)&0x03; + m_Size = ((pData[0]&0x3F)<<6) | (pData[1]&0x3F); + m_Sequence = -1; + if(m_Flags&NET_CHUNKFLAG_VITAL) + { + m_Sequence = ((pData[1]&0xC0)<<2) | pData[2]; + return pData + 3; + } + return pData + 2; +} + +void CNetBase::UpdateLogHandles() +{ + if(Engine()) + Engine()->QueryNetLogHandles(&m_DataLogSent, &m_DataLogRecv); +} diff --git a/src/engine/shared/network.h b/src/engine/shared/network.h new file mode 100644 index 000000000..263b9ac3a --- /dev/null +++ b/src/engine/shared/network.h @@ -0,0 +1,569 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_NETWORK_H +#define ENGINE_SHARED_NETWORK_H + +#include "ringbuffer.h" +#include "huffman.h" + +/* + +CURRENT: + packet header: 7 bytes (9 bytes for connless) + unsigned char flags_ack; // 6bit flags, 2bit ack + unsigned char ack; // 8bit ack + unsigned char numchunks; // 8bit chunks + unsigned char token[4]; // 32bit token + // ffffffaa + // aaaaaaaa + // NNNNNNNN + // TTTTTTTT + // TTTTTTTT + // TTTTTTTT + // TTTTTTTT + + packet header (CONNLESS): + unsigned char flag_version; // 6bit flags, 2bits version + unsigned char token[4]; // 32bit token + unsigned char responsetoken[4]; // 32bit response token + + // ffffffvv + // TTTTTTTT + // TTTTTTTT + // TTTTTTTT + // TTTTTTTT + // RRRRRRRR + // RRRRRRRR + // RRRRRRRR + // RRRRRRRR + + if the token isn't explicitely set by any means, it must be set to + 0xffffffff + + chunk header: 2-3 bytes + unsigned char flags_size; // 2bit flags, 6 bit size + unsigned char size_seq; // 6bit size, 2bit seq + (unsigned char seq;) // 8bit seq, if vital flag is set +*/ + +enum +{ + NETFLAG_ALLOWSTATELESS=1, + NETSENDFLAG_VITAL=1, + NETSENDFLAG_CONNLESS=2, + NETSENDFLAG_FLUSH=4, + + NETSTATE_OFFLINE=0, + NETSTATE_CONNECTING, + NETSTATE_ONLINE, + + NETBANTYPE_SOFT=1, + NETBANTYPE_DROP=2, + + NETCREATE_FLAG_RANDOMPORT=1, +}; + + +enum +{ + NET_MAX_CHUNKHEADERSIZE = 3, + + // packets + NET_PACKETHEADERSIZE = 7, + NET_PACKETHEADERSIZE_CONNLESS = NET_PACKETHEADERSIZE + 2, + NET_MAX_PACKETHEADERSIZE = NET_PACKETHEADERSIZE_CONNLESS, + + NET_MAX_PACKETSIZE = 1400, + NET_MAX_PAYLOAD = NET_MAX_PACKETSIZE-NET_MAX_PACKETHEADERSIZE, + + NET_PACKETVERSION=1, + + NET_PACKETFLAG_CONTROL=1, + NET_PACKETFLAG_RESEND=2, + NET_PACKETFLAG_COMPRESSION=4, + NET_PACKETFLAG_CONNLESS=8, + + NET_MAX_PACKET_CHUNKS=256, + + // token + NET_SEEDTIME = 16, + + NET_TOKENCACHE_SIZE = 64, + NET_TOKENCACHE_ADDRESSEXPIRY = NET_SEEDTIME, + NET_TOKENCACHE_PACKETEXPIRY = 5, +}; +enum +{ + NET_TOKEN_MAX = 0xffffffff, + NET_TOKEN_NONE = NET_TOKEN_MAX, + NET_TOKEN_MASK = NET_TOKEN_MAX, +}; +enum +{ + NET_TOKENFLAG_ALLOWBROADCAST = 1, + NET_TOKENFLAG_RESPONSEONLY = 2, + + NET_TOKENREQUEST_DATASIZE = 512, + + // + NET_MAX_CLIENTS = 64, + NET_MAX_CONSOLE_CLIENTS = 4, + + NET_MAX_SEQUENCE = 1<<10, + NET_SEQUENCE_MASK = NET_MAX_SEQUENCE-1, + + NET_CONNSTATE_OFFLINE=0, + NET_CONNSTATE_TOKEN=1, + NET_CONNSTATE_CONNECT=2, + NET_CONNSTATE_PENDING=3, + NET_CONNSTATE_ONLINE=4, + NET_CONNSTATE_ERROR=5, + + NET_CHUNKFLAG_VITAL=1, + NET_CHUNKFLAG_RESEND=2, + + NET_CTRLMSG_KEEPALIVE=0, + NET_CTRLMSG_CONNECT=1, + NET_CTRLMSG_ACCEPT=2, + NET_CTRLMSG_CLOSE=4, + NET_CTRLMSG_TOKEN=5, + + NET_CONN_BUFFERSIZE=1024*32, + + NET_ENUM_TERMINATOR +}; + + +typedef int (*NETFUNC_DELCLIENT)(int ClientID, const char* pReason, void *pUser); +typedef int (*NETFUNC_NEWCLIENT)(int ClientID, void *pUser); + +typedef unsigned int TOKEN; + +struct CNetChunk +{ + // -1 means that it's a connless packet + // 0 on the client means the server + int m_ClientID; + NETADDR m_Address; // only used when cid == -1 + int m_Flags; + int m_DataSize; + const void *m_pData; +}; + +class CNetChunkHeader +{ +public: + int m_Flags; + int m_Size; + int m_Sequence; + + unsigned char *Pack(unsigned char *pData); + unsigned char *Unpack(unsigned char *pData); +}; + +class CNetChunkResend +{ +public: + int m_Flags; + int m_DataSize; + unsigned char *m_pData; + + int m_Sequence; + int64 m_LastSendTime; + int64 m_FirstSendTime; +}; + +class CNetPacketConstruct +{ +public: + TOKEN m_Token; + TOKEN m_ResponseToken; // only used in connless packets + int m_Flags; + int m_Ack; + int m_NumChunks; + int m_DataSize; + unsigned char m_aChunkData[NET_MAX_PAYLOAD]; +}; + + +class CNetBase +{ + class CNetInitializer + { + public: + CNetInitializer() + { + // init the network + net_init(); + } + }; + static CNetInitializer m_NetInitializer; + + class CConfig *m_pConfig; + class IEngine *m_pEngine; + NETSOCKET m_Socket; + IOHANDLE m_DataLogSent; + IOHANDLE m_DataLogRecv; + CHuffman m_Huffman; + unsigned char m_aRequestTokenBuf[NET_TOKENREQUEST_DATASIZE]; + +public: + CNetBase(); + ~CNetBase(); + CConfig *Config() { return m_pConfig; } + class IEngine *Engine() { return m_pEngine; } + int NetType() { return m_Socket.type; } + + void Init(NETSOCKET Socket, class CConfig *pConfig, class IConsole *pConsole, class IEngine *pEngine); + void Shutdown(); + void UpdateLogHandles(); + void Wait(int Time); + + void SendControlMsg(const NETADDR *pAddr, TOKEN Token, int Ack, int ControlMsg, const void *pExtra, int ExtraSize); + void SendControlMsgWithToken(const NETADDR *pAddr, TOKEN Token, int Ack, int ControlMsg, TOKEN MyToken, bool Extended); + void SendPacketConnless(const NETADDR *pAddr, TOKEN Token, TOKEN ResponseToken, const void *pData, int DataSize); + void SendPacket(const NETADDR *pAddr, CNetPacketConstruct *pPacket); + int UnpackPacket(NETADDR *pAddr, unsigned char *pBuffer, CNetPacketConstruct *pPacket); +}; + +class CNetTokenManager +{ +public: + void Init(CNetBase *pNetBase, int SeedTime = NET_SEEDTIME); + void Update(); + + void GenerateSeed(); + + int ProcessMessage(const NETADDR *pAddr, const CNetPacketConstruct *pPacket); + + bool CheckToken(const NETADDR *pAddr, TOKEN Token, TOKEN ResponseToken, bool *BroadcastResponse); + TOKEN GenerateToken(const NETADDR *pAddr) const; + static TOKEN GenerateToken(const NETADDR *pAddr, int64 Seed); + +private: + CNetBase *m_pNetBase; + + int64 m_Seed; + int64 m_PrevSeed; + + TOKEN m_GlobalToken; + TOKEN m_PrevGlobalToken; + + int m_SeedTime; + int64 m_NextSeedTime; +}; + +typedef void(*FSendCallback)(int TrackID, void *pUser); +struct CSendCBData +{ + FSendCallback m_pfnCallback; + void *m_pCallbackUser; + int m_TrackID; +}; + +class CNetTokenCache +{ +public: + CNetTokenCache(); + ~CNetTokenCache(); + void Init(CNetBase *pNetBase, const CNetTokenManager *pTokenManager); + void SendPacketConnless(const NETADDR *pAddr, const void *pData, int DataSize, CSendCBData *pCallbackData = 0); + void PurgeStoredPacket(int TrackID); + void FetchToken(const NETADDR *pAddr); + void AddToken(const NETADDR *pAddr, TOKEN PeerToken, int TokenFlag); + TOKEN GetToken(const NETADDR *pAddr); + void Update(); + +private: + class CConnlessPacketInfo + { + private: + static int m_UniqueID; + + public: + CConnlessPacketInfo() : m_TrackID(CConnlessPacketInfo::m_UniqueID++) {} + + NETADDR m_Addr; + int m_DataSize; + char m_aData[NET_MAX_PAYLOAD]; + int64 m_Expiry; + int64 m_LastTokenRequest; + const int m_TrackID; + FSendCallback m_pfnCallback; + void *m_pCallbackUser; + CConnlessPacketInfo *m_pNext; + }; + + struct CAddressInfo + { + NETADDR m_Addr; + TOKEN m_Token; + int64 m_Expiry; + }; + + TStaticRingBuffer m_TokenCache; + + CConnlessPacketInfo *m_pConnlessPacketList; // TODO: enhance this, dynamic linked lists + // are bad for performance + CNetBase *m_pNetBase; + const CNetTokenManager *m_pTokenManager; +}; + + +class CNetConnection +{ + // TODO: is this needed because this needs to be aware of + // the ack sequencing number and is also responible for updating + // that. this should be fixed. + friend class CNetRecvUnpacker; +private: + unsigned short m_Sequence; + unsigned short m_Ack; + unsigned short m_PeerAck; + unsigned m_State; + + int m_RemoteClosed; + bool m_BlockCloseMsg; + + TStaticRingBuffer m_Buffer; + + int64 m_LastUpdateTime; + int64 m_LastRecvTime; + int64 m_LastSendTime; + + char m_ErrorString[256]; + + CNetPacketConstruct m_Construct; + + TOKEN m_Token; + TOKEN m_PeerToken; + NETADDR m_PeerAddr; + + NETSTATS m_Stats; + CNetBase *m_pNetBase; + + // + void Reset(); + void ResetStats(); + void SetError(const char *pString); + void AckChunks(int Ack); + + int QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence); + void SendControl(int ControlMsg, const void *pExtra, int ExtraSize); + void SendControlWithToken(int ControlMsg); + void ResendChunk(CNetChunkResend *pResend); + void Resend(); + + static TOKEN GenerateToken(const NETADDR *pPeerAddr); + +public: + void Init(CNetBase *pNetBase, bool BlockCloseMsg); + int Connect(NETADDR *pAddr); + void Disconnect(const char *pReason); + + void SetToken(TOKEN Token); + + TOKEN Token() const { return m_Token; } + TOKEN PeerToken() const { return m_PeerToken; } + class CConfig *Config() { return m_pNetBase->Config(); } + + int Update(); + int Flush(); + + int Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr); + int QueueChunk(int Flags, int DataSize, const void *pData); + void SendPacketConnless(const char *pData, int DataSize); + + const char *ErrorString(); + void SignalResend(); + int State() const { return m_State; } + const NETADDR *PeerAddress() const { return &m_PeerAddr; } + + void ResetErrorString() { m_ErrorString[0] = 0; } + const char *ErrorString() const { return m_ErrorString; } + + // Needed for GotProblems in NetClient + int64 LastRecvTime() const { return m_LastRecvTime; } + int64 ConnectTime() const { return m_LastUpdateTime; } + + int AckSequence() const { return m_Ack; } + // The backroom is ack-NET_MAX_SEQUENCE/2. Used for knowing if we acked a packet or not + static int IsSeqInBackroom(int Seq, int Ack); +}; + +class CConsoleNetConnection +{ +private: + int m_State; + + NETADDR m_PeerAddr; + NETSOCKET m_Socket; + + char m_aBuffer[NET_MAX_PACKETSIZE]; + int m_BufferOffset; + + char m_aErrorString[256]; + + bool m_LineEndingDetected; + char m_aLineEnding[3]; + +public: + void Init(NETSOCKET Socket, const NETADDR *pAddr); + void Disconnect(const char *pReason); + + int State() const { return m_State; } + const NETADDR *PeerAddress() const { return &m_PeerAddr; } + const char *ErrorString() const { return m_aErrorString; } + + void Reset(); + int Update(); + int Send(const char *pLine); + int Recv(char *pLine, int MaxLength); +}; + +class CNetRecvUnpacker +{ + bool m_Valid; + +public: + NETADDR m_Addr; + CNetConnection *m_pConnection; + int m_CurrentChunk; + int m_ClientID; + CNetPacketConstruct m_Data; + unsigned char m_aBuffer[NET_MAX_PACKETSIZE]; + + CNetRecvUnpacker() { Clear(); } + bool IsActive() { return m_Valid; } + void Clear(); + void Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID); + int FetchChunk(CNetChunk *pChunk); +}; + +// server side +class CNetServer : public CNetBase +{ + struct CSlot + { + public: + CNetConnection m_Connection; + }; + + class CNetBan *m_pNetBan; + CSlot m_aSlots[NET_MAX_CLIENTS]; + int m_NumClients; + int m_MaxClients; + int m_MaxClientsPerIP; + + NETFUNC_NEWCLIENT m_pfnNewClient; + NETFUNC_DELCLIENT m_pfnDelClient; + void *m_UserPtr; + + CNetRecvUnpacker m_RecvUnpacker; + + CNetTokenManager m_TokenManager; + CNetTokenCache m_TokenCache; + +public: + // + bool Open(NETADDR BindAddr, class CConfig *pConfig, class IConsole *pConsole, class IEngine *pEngine, class CNetBan *pNetBan, + int MaxClients, int MaxClientsPerIP, NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); + void Close(const char *pReason); + + // the token parameter is only used for connless packets + int Recv(CNetChunk *pChunk, TOKEN *pResponseToken = 0); + int Send(CNetChunk *pChunk, TOKEN Token = NET_TOKEN_NONE); + int Update(); + void AddToken(const NETADDR *pAddr, TOKEN Token) { m_TokenCache.AddToken(pAddr, Token, 0); } + + // + void Drop(int ClientID, const char *pReason); + + // status requests + const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } + class CNetBan *NetBan() const { return m_pNetBan; } + + // + void SetMaxClients(int MaxClients); + void SetMaxClientsPerIP(int MaxClientsPerIP); +}; + +class CNetConsole +{ + struct CSlot + { + CConsoleNetConnection m_Connection; + }; + + NETSOCKET m_Socket; + class CNetBan *m_pNetBan; + CSlot m_aSlots[NET_MAX_CONSOLE_CLIENTS]; + + NETFUNC_NEWCLIENT m_pfnNewClient; + NETFUNC_DELCLIENT m_pfnDelClient; + void *m_UserPtr; + + CNetRecvUnpacker m_RecvUnpacker; + +public: + // + bool Open(NETADDR BindAddr, class CNetBan *pNetBan, NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); + void Close(); + + // + int Recv(char *pLine, int MaxLength, int *pClientID = 0); + int Send(int ClientID, const char *pLine); + int Update(); + void SetLingerState(int State); + + // + int AcceptClient(NETSOCKET Socket, const NETADDR *pAddr); + void Drop(int ClientID, const char *pReason); + + // status requests + const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } + class CNetBan *NetBan() const { return m_pNetBan; } +}; + + + +// client side +class CNetClient : public CNetBase +{ + CNetConnection m_Connection; + CNetRecvUnpacker m_RecvUnpacker; + + CNetTokenCache m_TokenCache; + CNetTokenManager m_TokenManager; + + int m_Flags; + +public: + // openness + bool Open(NETADDR BindAddr, class CConfig *pConfig, class IConsole *pConsole, class IEngine *pEngine, int Flags); + void Close(); + + // connection state + int Disconnect(const char *Reason); + int Connect(NETADDR *Addr); + + // communication + int Recv(CNetChunk *pChunk, TOKEN *pResponseToken = 0); + int Send(CNetChunk *pChunk, TOKEN Token = NET_TOKEN_NONE, CSendCBData *pCallbackData = 0); + void PurgeStoredPacket(int TrackID); + + // pumping + int Update(); + int Flush(); + + int ResetErrorString(); + + // error and state + int State() const; + bool GotProblems() const; + const char *ErrorString() const; +}; + +#endif diff --git a/src/engine/shared/network_conn.cpp b/src/engine/shared/network_conn.cpp new file mode 100644 index 000000000..dac402ac1 --- /dev/null +++ b/src/engine/shared/network_conn.cpp @@ -0,0 +1,455 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include "config.h" +#include "network.h" + + +void CNetConnection::ResetStats() +{ + mem_zero(&m_Stats, sizeof(m_Stats)); +} + +void CNetConnection::Reset() +{ + m_Sequence = 0; + m_Ack = 0; + m_PeerAck = 0; + m_RemoteClosed = 0; + + m_State = NET_CONNSTATE_OFFLINE; + m_LastSendTime = 0; + m_LastRecvTime = 0; + m_LastUpdateTime = 0; + m_Token = NET_TOKEN_NONE; + m_PeerToken = NET_TOKEN_NONE; + mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); + + m_Buffer.Init(); + + mem_zero(&m_Construct, sizeof(m_Construct)); +} + +void CNetConnection::SetToken(TOKEN Token) +{ + if(State() != NET_CONNSTATE_OFFLINE) + return; + + m_Token = Token; +} + +TOKEN CNetConnection::GenerateToken(const NETADDR *pPeerAddr) +{ + return random_int() & NET_TOKEN_MASK; +} + +const char *CNetConnection::ErrorString() +{ + return m_ErrorString; +} + +void CNetConnection::SetError(const char *pString) +{ + str_copy(m_ErrorString, pString, sizeof(m_ErrorString)); +} + +void CNetConnection::Init(CNetBase *pNetBase, bool BlockCloseMsg) +{ + Reset(); + ResetStats(); + + m_pNetBase = pNetBase; + m_BlockCloseMsg = BlockCloseMsg; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); +} + +void CNetConnection::AckChunks(int Ack) +{ + while(1) + { + CNetChunkResend *pResend = m_Buffer.First(); + if(!pResend) + break; + + if(IsSeqInBackroom(pResend->m_Sequence, Ack)) + m_Buffer.PopFirst(); + else + break; + } +} + +void CNetConnection::SignalResend() +{ + m_Construct.m_Flags |= NET_PACKETFLAG_RESEND; +} + +int CNetConnection::Flush() +{ + int NumChunks = m_Construct.m_NumChunks; + if(!NumChunks && !m_Construct.m_Flags) + return 0; + + // send of the packets + m_Construct.m_Ack = m_Ack; + m_Construct.m_Token = m_PeerToken; + m_pNetBase->SendPacket(&m_PeerAddr, &m_Construct); + + // update send times + m_LastSendTime = time_get(); + + // clear construct so we can start building a new package + mem_zero(&m_Construct, sizeof(m_Construct)); + return NumChunks; +} + +int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence) +{ + unsigned char *pChunkData; + + // check if we have space for it, if not, flush the connection + if(m_Construct.m_DataSize + DataSize + NET_MAX_CHUNKHEADERSIZE > (int)sizeof(m_Construct.m_aChunkData) || m_Construct.m_NumChunks == NET_MAX_PACKET_CHUNKS) + Flush(); + + // pack all the data + CNetChunkHeader Header; + Header.m_Flags = Flags; + Header.m_Size = DataSize; + Header.m_Sequence = Sequence; + pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize]; + pChunkData = Header.Pack(pChunkData); + mem_copy(pChunkData, pData, DataSize); + pChunkData += DataSize; + + // + m_Construct.m_NumChunks++; + m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); + + // set packet flags aswell + + if(Flags&NET_CHUNKFLAG_VITAL && !(Flags&NET_CHUNKFLAG_RESEND)) + { + // save packet if we need to resend + CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+DataSize); + if(pResend) + { + pResend->m_Sequence = Sequence; + pResend->m_Flags = Flags; + pResend->m_DataSize = DataSize; + pResend->m_pData = (unsigned char *)(pResend+1); + pResend->m_FirstSendTime = time_get(); + pResend->m_LastSendTime = pResend->m_FirstSendTime; + mem_copy(pResend->m_pData, pData, DataSize); + } + else + { + // out of buffer + Disconnect("too weak connection (out of buffer)"); + return -1; + } + } + + return 0; +} + +int CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData) +{ + if(Flags&NET_CHUNKFLAG_VITAL) + m_Sequence = (m_Sequence+1)%NET_MAX_SEQUENCE; + return QueueChunkEx(Flags, DataSize, pData, m_Sequence); +} + +void CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSize) +{ + // send the control message + m_LastSendTime = time_get(); + m_pNetBase->SendControlMsg(&m_PeerAddr, m_PeerToken, m_Ack, ControlMsg, pExtra, ExtraSize); +} + +void CNetConnection::SendPacketConnless(const char *pData, int DataSize) +{ + m_pNetBase->SendPacketConnless(&m_PeerAddr, m_PeerToken, m_Token, pData, DataSize); +} + +void CNetConnection::SendControlWithToken(int ControlMsg) +{ + m_LastSendTime = time_get(); + m_pNetBase->SendControlMsgWithToken(&m_PeerAddr, m_PeerToken, 0, ControlMsg, m_Token, true); +} + +void CNetConnection::ResendChunk(CNetChunkResend *pResend) +{ + QueueChunkEx(pResend->m_Flags|NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence); + pResend->m_LastSendTime = time_get(); +} + +void CNetConnection::Resend() +{ + for(CNetChunkResend *pResend = m_Buffer.First(); pResend; pResend = m_Buffer.Next(pResend)) + ResendChunk(pResend); +} + +int CNetConnection::Connect(NETADDR *pAddr) +{ + if(State() != NET_CONNSTATE_OFFLINE) + return -1; + + // init connection + Reset(); + m_LastRecvTime = time_get(); + m_PeerAddr = *pAddr; + m_PeerToken = NET_TOKEN_NONE; + SetToken(GenerateToken(pAddr)); + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + m_State = NET_CONNSTATE_TOKEN; + SendControlWithToken(NET_CTRLMSG_TOKEN); + return 0; +} + +void CNetConnection::Disconnect(const char *pReason) +{ + if(State() == NET_CONNSTATE_OFFLINE) + return; + + if(m_RemoteClosed == 0) + { + if(pReason) + SendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason)+1); + else + SendControl(NET_CTRLMSG_CLOSE, 0, 0); + + if(pReason != m_ErrorString) + { + if(pReason) + str_copy(m_ErrorString, pReason, sizeof(m_ErrorString)); + else + m_ErrorString[0] = 0; + } + } + + Reset(); +} + +int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) +{ + // check if actual ack value is valid(own sequence..latest peer ack) + if(m_Sequence >= m_PeerAck) + { + if(pPacket->m_Ack < m_PeerAck || pPacket->m_Ack > m_Sequence) + return 0; + } + else + { + if(pPacket->m_Ack < m_PeerAck && pPacket->m_Ack > m_Sequence) + return 0; + } + m_PeerAck = pPacket->m_Ack; + + int64 Now = time_get(); + + if(pPacket->m_Token == NET_TOKEN_NONE || pPacket->m_Token != m_Token) + return 0; + + // check if resend is requested + if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) + Resend(); + + if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) + return 1; + + // + if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) + { + int CtrlMsg = pPacket->m_aChunkData[0]; + + if(CtrlMsg == NET_CTRLMSG_CLOSE) + { + if(net_addr_comp(&m_PeerAddr, pAddr, true) == 0) + { + m_State = NET_CONNSTATE_ERROR; + m_RemoteClosed = 1; + + char Str[128] = {0}; + if(pPacket->m_DataSize > 1) + { + // make sure to sanitize the error string form the other party + if(pPacket->m_DataSize < 128) + str_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize); + else + str_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str)); + str_sanitize_strong(Str); + } + + if(!m_BlockCloseMsg) + { + // set the error string + SetError(Str); + } + + if(Config()->m_Debug) + dbg_msg("conn", "closed reason='%s'", Str); + } + return 0; + } + else + { + if(CtrlMsg == NET_CTRLMSG_TOKEN) + { + m_PeerToken = pPacket->m_ResponseToken; + + if(State() == NET_CONNSTATE_TOKEN) + { + m_LastRecvTime = Now; + m_State = NET_CONNSTATE_CONNECT; + SendControlWithToken(NET_CTRLMSG_CONNECT); + dbg_msg("connection", "got token, replying, token=%x mytoken=%x", m_PeerToken, m_Token); + } + else if(Config()->m_Debug) + dbg_msg("connection", "got token, token=%x", m_PeerToken); + } + else + { + if(State() == NET_CONNSTATE_OFFLINE) + { + if(CtrlMsg == NET_CTRLMSG_CONNECT) + { + // send response and init connection + TOKEN Token = m_Token; + Reset(); + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + m_State = NET_CONNSTATE_PENDING; + m_PeerAddr = *pAddr; + m_PeerToken = pPacket->m_ResponseToken; + m_Token = Token; + m_LastSendTime = Now; + m_LastRecvTime = Now; + m_LastUpdateTime = Now; + SendControl(NET_CTRLMSG_ACCEPT, 0, 0); + if(Config()->m_Debug) + dbg_msg("connection", "got connection, sending accept"); + } + } + else if(State() == NET_CONNSTATE_CONNECT) + { + // connection made + if(CtrlMsg == NET_CTRLMSG_ACCEPT) + { + m_LastRecvTime = Now; + m_State = NET_CONNSTATE_ONLINE; + if(Config()->m_Debug) + dbg_msg("connection", "got accept. connection online"); + } + } + } + } + } + else + { + if(State() == NET_CONNSTATE_PENDING) + { + m_LastRecvTime = Now; + m_State = NET_CONNSTATE_ONLINE; + if(Config()->m_Debug) + dbg_msg("connection", "connecting online"); + } + } + + if(State() == NET_CONNSTATE_ONLINE) + { + m_LastRecvTime = Now; + AckChunks(pPacket->m_Ack); + } + + return 1; +} + +int CNetConnection::Update() +{ + int64 Now = time_get(); + + if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR) + return 0; + + // check for timeout + if(State() != NET_CONNSTATE_OFFLINE && + State() != NET_CONNSTATE_TOKEN && + (Now-m_LastRecvTime) > time_freq()*10) + { + m_State = NET_CONNSTATE_ERROR; + SetError("Timeout"); + } + else if(State() == NET_CONNSTATE_TOKEN && (Now - m_LastRecvTime) > time_freq() * 5) + { + m_State = NET_CONNSTATE_ERROR; + SetError("Unable to connect to the server"); + } + + // fix resends + if(m_Buffer.First()) + { + CNetChunkResend *pResend = m_Buffer.First(); + + // check if we have some really old stuff laying around and abort if not acked + if(Now-pResend->m_FirstSendTime > time_freq()*10) + { + m_State = NET_CONNSTATE_ERROR; + SetError("Too weak connection (not acked for 10 seconds)"); + } + else + { + // resend packet if we haven't got it acked in 1 second + if(Now-pResend->m_LastSendTime > time_freq()) + ResendChunk(pResend); + } + } + + // send keep alives if nothing has happend for 250ms + if(State() == NET_CONNSTATE_ONLINE) + { + if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed + { + int NumFlushedChunks = Flush(); + if(NumFlushedChunks && Config()->m_Debug) + dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks); + } + + if(time_get()-m_LastSendTime > time_freq()) + SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0); + } + else if(State() == NET_CONNSTATE_TOKEN) + { + if(time_get()-m_LastSendTime > time_freq()/2) // send a new token request every 500ms + SendControlWithToken(NET_CTRLMSG_TOKEN); + } + else if(State() == NET_CONNSTATE_CONNECT) + { + if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms + SendControlWithToken(NET_CTRLMSG_CONNECT); + } + else if(State() == NET_CONNSTATE_PENDING) + { + if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms + SendControl(NET_CTRLMSG_ACCEPT, 0, 0); + } + + return 0; +} + +int CNetConnection::IsSeqInBackroom(int Seq, int Ack) +{ + int Bottom = (Ack - NET_MAX_SEQUENCE / 2); + if(Bottom < 0) + { + if(Seq <= Ack) + return 1; + if(Seq >= (Bottom + NET_MAX_SEQUENCE)) + return 1; + } + else + { + if(Seq <= Ack && Seq >= Bottom) + return 1; + } + + return 0; +} diff --git a/src/engine/shared/network_console.cpp b/src/engine/shared/network_console.cpp new file mode 100644 index 000000000..0ad443cd2 --- /dev/null +++ b/src/engine/shared/network_console.cpp @@ -0,0 +1,156 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +#include "netban.h" +#include "network.h" + + +bool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) +{ + // zero out the whole structure + mem_zero(this, sizeof(*this)); + m_Socket.type = NETTYPE_INVALID; + m_Socket.ipv4sock = -1; + m_Socket.ipv6sock = -1; + m_pNetBan = pNetBan; + + // open socket + m_Socket = net_tcp_create(BindAddr); + if(!m_Socket.type) + return false; + if(net_tcp_listen(m_Socket, NET_MAX_CONSOLE_CLIENTS)) + return false; + net_set_non_blocking(m_Socket); + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + m_aSlots[i].m_Connection.Reset(); + + m_pfnNewClient = pfnNewClient; + m_pfnDelClient = pfnDelClient; + m_UserPtr = pUser; + + return true; +} + +void CNetConsole::Close() +{ + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + Drop(i, "Closing console"); + + net_tcp_close(m_Socket); +} + +void CNetConsole::Drop(int ClientID, const char *pReason) +{ + if(ClientID < 0 || ClientID >= NET_MAX_CONSOLE_CLIENTS || m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_OFFLINE) + return; + + if(m_pfnDelClient) + m_pfnDelClient(ClientID, pReason, m_UserPtr); + + m_aSlots[ClientID].m_Connection.Disconnect(pReason); +} + +int CNetConsole::AcceptClient(NETSOCKET Socket, const NETADDR *pAddr) +{ + char aError[256] = { 0 }; + int FreeSlot = -1; + + // look for free slot or multiple client + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(FreeSlot == -1 && m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + FreeSlot = i; + if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE) + { + if(net_addr_comp(pAddr, m_aSlots[i].m_Connection.PeerAddress(), true) == 0) + { + str_copy(aError, "only one client per IP allowed", sizeof(aError)); + break; + } + } + } + + // accept client + if(!aError[0] && FreeSlot != -1) + { + m_aSlots[FreeSlot].m_Connection.Init(Socket, pAddr); + if(m_pfnNewClient) + m_pfnNewClient(FreeSlot, m_UserPtr); + return 0; + } + + // reject client + if(!aError[0]) + str_copy(aError, "no free slot available", sizeof(aError)); + + net_tcp_send(Socket, aError, str_length(aError)); + net_tcp_close(Socket); + + return -1; +} + +int CNetConsole::Update() +{ + NETSOCKET Socket; + NETADDR Addr; + + if(net_tcp_accept(m_Socket, &Socket, &Addr) > 0) + { + // check if we just should drop the packet + char aBuf[128]; + int LastInfoQuery; + if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf), &LastInfoQuery)) + { + // banned, reply with a message (5 second cooldown) and drop + int Time = time_timestamp(); + if(LastInfoQuery + 5 < Time) + { + net_tcp_send(Socket, aBuf, str_length(aBuf)); + } + net_tcp_close(Socket); + } + else + AcceptClient(Socket, &Addr); + } + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE) + m_aSlots[i].m_Connection.Update(); + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) + Drop(i, m_aSlots[i].m_Connection.ErrorString()); + } + + return 0; +} + +int CNetConsole::Recv(char *pLine, int MaxLength, int *pClientID) +{ + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE && m_aSlots[i].m_Connection.Recv(pLine, MaxLength)) + { + if(pClientID) + *pClientID = i; + return 1; + } + } + return 0; +} + +int CNetConsole::Send(int ClientID, const char *pLine) +{ + if(m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_ONLINE) + return m_aSlots[ClientID].m_Connection.Send(pLine); + else + return -1; +} + +void CNetConsole::SetLingerState(int State) +{ + net_tcp_set_linger(m_Socket, State); +} diff --git a/src/engine/shared/network_console_conn.cpp b/src/engine/shared/network_console_conn.cpp new file mode 100644 index 000000000..9bc163aff --- /dev/null +++ b/src/engine/shared/network_console_conn.cpp @@ -0,0 +1,186 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include "network.h" + +void CConsoleNetConnection::Reset() +{ + m_State = NET_CONNSTATE_OFFLINE; + mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); + m_aErrorString[0] = 0; + + m_Socket.type = NETTYPE_INVALID; + m_Socket.ipv4sock = -1; + m_Socket.ipv6sock = -1; + m_aBuffer[0] = 0; + m_BufferOffset = 0; + + m_LineEndingDetected = false; + #if defined(CONF_FAMILY_WINDOWS) + m_aLineEnding[0] = '\r'; + m_aLineEnding[1] = '\n'; + m_aLineEnding[2] = 0; + #else + m_aLineEnding[0] = '\n'; + m_aLineEnding[1] = 0; + m_aLineEnding[2] = 0; + #endif +} + +void CConsoleNetConnection::Init(NETSOCKET Socket, const NETADDR *pAddr) +{ + Reset(); + + m_Socket = Socket; + net_set_non_blocking(m_Socket); + + m_PeerAddr = *pAddr; + m_State = NET_CONNSTATE_ONLINE; +} + +void CConsoleNetConnection::Disconnect(const char *pReason) +{ + if(State() == NET_CONNSTATE_OFFLINE) + return; + + if(pReason && pReason[0]) + Send(pReason); + + net_tcp_close(m_Socket); + + Reset(); +} + +int CConsoleNetConnection::Update() +{ + if(State() == NET_CONNSTATE_ONLINE) + { + if((int)(sizeof(m_aBuffer)) <= m_BufferOffset) + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "too weak connection (out of buffer)", sizeof(m_aErrorString)); + return -1; + } + + int Bytes = net_tcp_recv(m_Socket, m_aBuffer+m_BufferOffset, (int)(sizeof(m_aBuffer))-m_BufferOffset); + + if(Bytes > 0) + { + m_BufferOffset += Bytes; + } + else if(Bytes < 0) + { + if(net_would_block()) // no data received + return 0; + + m_State = NET_CONNSTATE_ERROR; // error + str_copy(m_aErrorString, "connection failure", sizeof(m_aErrorString)); + return -1; + } + else + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "remote end closed the connection", sizeof(m_aErrorString)); + return -1; + } + } + + return 0; +} + +int CConsoleNetConnection::Recv(char *pLine, int MaxLength) +{ + if(State() == NET_CONNSTATE_ONLINE) + { + if(m_BufferOffset) + { + // find message start + int StartOffset = 0; + while(m_aBuffer[StartOffset] == '\r' || m_aBuffer[StartOffset] == '\n') + { + // detect clients line ending format + if(!m_LineEndingDetected) + { + m_aLineEnding[0] = m_aBuffer[StartOffset]; + if(StartOffset+1 < m_BufferOffset && (m_aBuffer[StartOffset+1] == '\r' || m_aBuffer[StartOffset+1] == '\n') && + m_aBuffer[StartOffset] != m_aBuffer[StartOffset+1]) + m_aLineEnding[1] = m_aBuffer[StartOffset+1]; + m_LineEndingDetected = true; + } + + if(++StartOffset >= m_BufferOffset) + { + m_BufferOffset = 0; + return 0; + } + } + + // find message end + int EndOffset = StartOffset; + while(m_aBuffer[EndOffset] != '\r' && m_aBuffer[EndOffset] != '\n') + { + if(++EndOffset >= m_BufferOffset) + { + if(StartOffset > 0) + { + mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + m_BufferOffset -= StartOffset; + } + return 0; + } + } + + // extract message and update buffer + if(MaxLength-1 < EndOffset-StartOffset) + { + if(StartOffset > 0) + { + mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + m_BufferOffset -= StartOffset; + } + return 0; + } + mem_copy(pLine, m_aBuffer+StartOffset, EndOffset-StartOffset); + pLine[EndOffset-StartOffset] = 0; + str_sanitize_cc(pLine); + mem_move(m_aBuffer, m_aBuffer+EndOffset, m_BufferOffset-EndOffset); + m_BufferOffset -= EndOffset; + return 1; + } + } + return 0; +} + +int CConsoleNetConnection::Send(const char *pLine) +{ + if(State() != NET_CONNSTATE_ONLINE) + return -1; + + char aBuf[1024]; + str_copy(aBuf, pLine, (int)(sizeof(aBuf))-2); + int Length = str_length(aBuf); + aBuf[Length] = m_aLineEnding[0]; + aBuf[Length+1] = m_aLineEnding[1]; + aBuf[Length+2] = m_aLineEnding[2]; + Length += 3; + const char *pData = aBuf; + + while(true) + { + int Send = net_tcp_send(m_Socket, pData, Length); + if(Send < 0) + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "failed to send packet", sizeof(m_aErrorString)); + return -1; + } + + if(Send >= Length) + break; + + pData += Send; + Length -= Send; + } + + return 0; +} diff --git a/src/engine/shared/network_server.cpp b/src/engine/shared/network_server.cpp new file mode 100644 index 000000000..011a2bc98 --- /dev/null +++ b/src/engine/shared/network_server.cpp @@ -0,0 +1,316 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include + +#include "netban.h" +#include "network.h" + + +bool CNetServer::Open(NETADDR BindAddr, CConfig *pConfig, IConsole *pConsole, IEngine *pEngine, CNetBan *pNetBan, + int MaxClients, int MaxClientsPerIP, NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) +{ + // zero out the whole structure + mem_zero(this, sizeof(*this)); + + // open socket + NETSOCKET Socket = net_udp_create(BindAddr, 0); + if(!Socket.type) + return false; + + // init + m_pNetBan = pNetBan; + Init(Socket, pConfig, pConsole, pEngine); + + m_TokenManager.Init(this); + m_TokenCache.Init(this, &m_TokenManager); + + m_NumClients = 0; + SetMaxClients(MaxClients); + SetMaxClientsPerIP(MaxClientsPerIP); + + for(int i = 0; i < NET_MAX_CLIENTS; i++) + m_aSlots[i].m_Connection.Init(this, true); + + m_pfnNewClient = pfnNewClient; + m_pfnDelClient = pfnDelClient; + m_UserPtr = pUser; + + return true; +} + +void CNetServer::Close(const char *pReason) +{ + for(int i = 0; i < NET_MAX_CLIENTS; i++) + Drop(i, pReason); + + Shutdown(); +} + +void CNetServer::Drop(int ClientID, const char *pReason) +{ + if(ClientID < 0 || ClientID >= NET_MAX_CLIENTS || m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_OFFLINE) + return; + + if(m_pfnDelClient) + m_pfnDelClient(ClientID, pReason, m_UserPtr); + + m_aSlots[ClientID].m_Connection.Disconnect(pReason); + m_NumClients--; +} + +int CNetServer::Update() +{ + int64 Now = time_get(); + for(int i = 0; i < NET_MAX_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + continue; + + m_aSlots[i].m_Connection.Update(); + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) + { + if(Now - m_aSlots[i].m_Connection.ConnectTime() < time_freq() && NetBan()) + { + if(NetBan()->BanAddr(ClientAddr(i), 60, "Stressing network") == -1) + Drop(i, m_aSlots[i].m_Connection.ErrorString()); + } + else + Drop(i, m_aSlots[i].m_Connection.ErrorString()); + } + } + + m_TokenManager.Update(); + m_TokenCache.Update(); + + return 0; +} + +/* + TODO: chopp up this function into smaller working parts +*/ +int CNetServer::Recv(CNetChunk *pChunk, TOKEN *pResponseToken) +{ + while(1) + { + // check for a chunk + if(m_RecvUnpacker.IsActive() && m_RecvUnpacker.FetchChunk(pChunk)) + return 1; + + // TODO: empty the recvinfo + NETADDR Addr; + int Result = UnpackPacket(&Addr, m_RecvUnpacker.m_aBuffer, &m_RecvUnpacker.m_Data); + // no more packets for now + if(Result > 0) + break; + + if(!Result) + { + // check for bans + char aBuf[128]; + int LastInfoQuery; + if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf), &LastInfoQuery)) + { + // banned, reply with a message (5 second cooldown) + int Time = time_timestamp(); + if(LastInfoQuery + 5 < Time) + { + SendControlMsg(&Addr, m_RecvUnpacker.m_Data.m_ResponseToken, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf) + 1); + } + continue; + } + + bool Found = false; + // try to find matching slot + for(int i = 0; i < NET_MAX_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + continue; + + if(net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr, true) == 0) + { + if(m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) + { + if(m_RecvUnpacker.m_Data.m_DataSize) + { + if(!(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS)) + m_RecvUnpacker.Start(&Addr, &m_aSlots[i].m_Connection, i); + else + { + pChunk->m_Flags = NETSENDFLAG_CONNLESS; + pChunk->m_Address = *m_aSlots[i].m_Connection.PeerAddress(); + pChunk->m_ClientID = i; + pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; + pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; + if(pResponseToken) + *pResponseToken = NET_TOKEN_NONE; + return 1; + } + } + } + Found = true; + } + } + + if(Found) + continue; + + int Accept = m_TokenManager.ProcessMessage(&Addr, &m_RecvUnpacker.m_Data); + if(Accept <= 0) + continue; + + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL) + { + if(m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_CONNECT) + { + // check if there are free slots + if(m_NumClients >= m_MaxClients) + { + const char FullMsg[] = "This server is full"; + SendControlMsg(&Addr, m_RecvUnpacker.m_Data.m_ResponseToken, 0, NET_CTRLMSG_CLOSE, FullMsg, sizeof(FullMsg)); + continue; + } + + // only allow a specific number of players with the same ip + int FoundAddr = 1; + + bool Continue = false; + for(int i = 0; i < NET_MAX_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + continue; + + if(!net_addr_comp(&Addr, m_aSlots[i].m_Connection.PeerAddress(), false)) + { + if(FoundAddr++ >= m_MaxClientsPerIP) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Only %d players with the same IP are allowed", m_MaxClientsPerIP); + SendControlMsg(&Addr, m_RecvUnpacker.m_Data.m_ResponseToken, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf) + 1); + Continue = true; + break; + } + } + } + + if(Continue) + continue; + + for(int i = 0; i < NET_MAX_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + { + m_NumClients++; + m_aSlots[i].m_Connection.SetToken(m_RecvUnpacker.m_Data.m_Token); + m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr); + if(m_pfnNewClient) + m_pfnNewClient(i, m_UserPtr); + break; + } + } + } + else if(m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_TOKEN) + m_TokenCache.AddToken(&Addr, m_RecvUnpacker.m_Data.m_ResponseToken, NET_TOKENFLAG_RESPONSEONLY); + } + else if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) + { + pChunk->m_Flags = NETSENDFLAG_CONNLESS; + pChunk->m_ClientID = -1; + pChunk->m_Address = Addr; + pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; + pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; + if(pResponseToken) + *pResponseToken = m_RecvUnpacker.m_Data.m_ResponseToken; + return 1; + } + } + } + return 0; +} + +int CNetServer::Send(CNetChunk *pChunk, TOKEN Token) +{ + if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) + { + if(pChunk->m_DataSize >= NET_MAX_PAYLOAD) + { + dbg_msg("netserver", "packet payload too big. %d. dropping packet", pChunk->m_DataSize); + return -1; + } + + if(pChunk->m_ClientID == -1) + { + for(int i = 0; i < NET_MAX_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + continue; + + if(net_addr_comp(&pChunk->m_Address, m_aSlots[i].m_Connection.PeerAddress(), true) == 0) + { + // upgrade the packet, now that we know its recipent + pChunk->m_ClientID = i; + break; + } + } + } + + if(Token != NET_TOKEN_NONE) + { + SendPacketConnless(&pChunk->m_Address, Token, m_TokenManager.GenerateToken(&pChunk->m_Address), pChunk->m_pData, pChunk->m_DataSize); + } + else + { + if(pChunk->m_ClientID == -1) + { + m_TokenCache.SendPacketConnless(&pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize); + } + else + { + dbg_assert(pChunk->m_ClientID >= 0, "errornous client id"); + dbg_assert(pChunk->m_ClientID < NET_MAX_CLIENTS, "errornous client id"); + dbg_assert(m_aSlots[pChunk->m_ClientID].m_Connection.State() != NET_CONNSTATE_OFFLINE, "errornous client id"); + + m_aSlots[pChunk->m_ClientID].m_Connection.SendPacketConnless((const char *)pChunk->m_pData, pChunk->m_DataSize); + } + } + } + else + { + if(pChunk->m_DataSize+NET_MAX_CHUNKHEADERSIZE >= NET_MAX_PAYLOAD) + { + dbg_msg("netclient", "chunk payload too big. %d. dropping chunk", pChunk->m_DataSize); + return -1; + } + + int Flags = 0; + dbg_assert(pChunk->m_ClientID >= 0, "errornous client id"); + dbg_assert(pChunk->m_ClientID < NET_MAX_CLIENTS, "errornous client id"); + dbg_assert(m_aSlots[pChunk->m_ClientID].m_Connection.State() != NET_CONNSTATE_OFFLINE, "errornous client id"); + + if(pChunk->m_Flags&NETSENDFLAG_VITAL) + Flags = NET_CHUNKFLAG_VITAL; + + if(m_aSlots[pChunk->m_ClientID].m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData) == 0) + { + if(pChunk->m_Flags&NETSENDFLAG_FLUSH) + m_aSlots[pChunk->m_ClientID].m_Connection.Flush(); + } + else + { + Drop(pChunk->m_ClientID, "Error sending data"); + } + } + return 0; +} + +void CNetServer::SetMaxClients(int MaxClients) +{ + m_MaxClients = clamp(MaxClients, 1, int(NET_MAX_CLIENTS)); +} + +void CNetServer::SetMaxClientsPerIP(int MaxClientsPerIP) +{ + m_MaxClientsPerIP = clamp(MaxClientsPerIP, 1, int(NET_MAX_CLIENTS)); +} diff --git a/src/engine/shared/network_token.cpp b/src/engine/shared/network_token.cpp new file mode 100644 index 000000000..78c374181 --- /dev/null +++ b/src/engine/shared/network_token.cpp @@ -0,0 +1,330 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include +#include +#include + +#include "network.h" + +static unsigned int Hash(char *pData, int Size) +{ + unsigned aDigest[4]; + MD5_DIGEST Digest = md5(pData, Size); + for(int i = 0; i < 4; i++) + aDigest[i] = bytes_be_to_uint(&Digest.data[i * 4]); + + return (aDigest[0] ^ aDigest[1] ^ aDigest[2] ^ aDigest[3]); +} + +int CNetTokenCache::CConnlessPacketInfo::m_UniqueID = 0; + +void CNetTokenManager::Init(CNetBase *pNetBase, int SeedTime) +{ + m_pNetBase = pNetBase; + m_SeedTime = SeedTime; + GenerateSeed(); +} + +void CNetTokenManager::Update() +{ + if(time_get() > m_NextSeedTime) + GenerateSeed(); +} + +int CNetTokenManager::ProcessMessage(const NETADDR *pAddr, const CNetPacketConstruct *pPacket) +{ + bool BroadcastResponse = false; + if(pPacket->m_Token != NET_TOKEN_NONE + && !CheckToken(pAddr, pPacket->m_Token, pPacket->m_ResponseToken, &BroadcastResponse)) + return 0; // wrong token, silent ignore + + bool Verified = pPacket->m_Token != NET_TOKEN_NONE; + bool TokenMessage = (pPacket->m_Flags & NET_PACKETFLAG_CONTROL) + && pPacket->m_aChunkData[0] == NET_CTRLMSG_TOKEN; + + if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) + return (Verified && !BroadcastResponse) ? 1 : 0; // connless packets without token are not allowed + + if(!TokenMessage) + { + if(Verified && !BroadcastResponse) + return 1; // verified packet + else + // the only allowed not connless packet + // without token is NET_CTRLMSG_TOKEN + return 0; + } + + if(Verified && TokenMessage) + return BroadcastResponse ? -1 : 1; // everything is fine, token exchange complete + + // client requesting token + if(pPacket->m_DataSize >= NET_TOKENREQUEST_DATASIZE) + { + m_pNetBase->SendControlMsgWithToken((NETADDR *)pAddr, pPacket->m_ResponseToken, 0, NET_CTRLMSG_TOKEN, GenerateToken(pAddr), false); + } + return 0; // no need to process NET_CTRLMSG_TOKEN further +} + +void CNetTokenManager::GenerateSeed() +{ + static const NETADDR NullAddr = { 0 }; + m_PrevSeed = m_Seed; + + secure_random_fill(&m_Seed, sizeof(m_Seed)); + + m_PrevGlobalToken = m_GlobalToken; + m_GlobalToken = GenerateToken(&NullAddr); + + m_NextSeedTime = time_get() + time_freq() * m_SeedTime; +} + +TOKEN CNetTokenManager::GenerateToken(const NETADDR *pAddr) const +{ + return GenerateToken(pAddr, m_Seed); +} + +TOKEN CNetTokenManager::GenerateToken(const NETADDR *pAddr, int64 Seed) +{ + static const NETADDR NullAddr = { 0 }; + NETADDR Addr; + char aBuf[sizeof(NETADDR) + sizeof(int64)]; + unsigned int Result; + + if(pAddr->type & NETTYPE_LINK_BROADCAST) + return GenerateToken(&NullAddr, Seed); + + mem_zero(&Addr, sizeof(NETADDR)); + mem_copy(Addr.ip, pAddr->ip, sizeof(Addr.ip)); + Addr.type = pAddr->type; + + mem_copy(aBuf, &Addr, sizeof(NETADDR)); + mem_copy(aBuf + sizeof(NETADDR), &Seed, sizeof(int64)); + + Result = Hash(aBuf, sizeof(aBuf)) & NET_TOKEN_MASK; + if(Result == NET_TOKEN_NONE) + Result--; + + return Result; +} + +bool CNetTokenManager::CheckToken(const NETADDR *pAddr, TOKEN Token, TOKEN ResponseToken, bool *BroadcastResponse) +{ + TOKEN CurrentToken = GenerateToken(pAddr, m_Seed); + if(CurrentToken == Token) + return true; + + if(GenerateToken(pAddr, m_PrevSeed) == Token) + { + // no need to notify the peer, just a one time thing + return true; + } + else if(Token == m_GlobalToken) + { + *BroadcastResponse = true; + return true; + } + else if(Token == m_PrevGlobalToken) + { + // no need to notify the peer, just a broadcast token response + *BroadcastResponse = true; + return true; + } + + return false; +} + + +CNetTokenCache::CNetTokenCache() +{ + m_pTokenManager = 0; + m_pConnlessPacketList = 0; +} + +CNetTokenCache::~CNetTokenCache() +{ + // delete the linked list + while(m_pConnlessPacketList) + { + CConnlessPacketInfo *pTemp = m_pConnlessPacketList->m_pNext; + delete m_pConnlessPacketList; + m_pConnlessPacketList = pTemp; + } + m_pConnlessPacketList = 0; +} + +void CNetTokenCache::Init(CNetBase *pNetBase, const CNetTokenManager *pTokenManager) +{ + // call the destructor to clear the linked list + this->~CNetTokenCache(); + + m_TokenCache.Init(); + m_pNetBase = pNetBase; + m_pTokenManager = pTokenManager; +} + +void CNetTokenCache::SendPacketConnless(const NETADDR *pAddr, const void *pData, int DataSize, CSendCBData *pCallbackData) +{ + TOKEN Token = GetToken(pAddr); + if(Token != NET_TOKEN_NONE) + { + m_pNetBase->SendPacketConnless(pAddr, Token, m_pTokenManager->GenerateToken(pAddr), pData, DataSize); + } + else + { + FetchToken(pAddr); + + // store the packet for future sending + CConnlessPacketInfo **ppInfo = &m_pConnlessPacketList; + while(*ppInfo) + ppInfo = &(*ppInfo)->m_pNext; + *ppInfo = new CConnlessPacketInfo(); + mem_copy((*ppInfo)->m_aData, pData, DataSize); + (*ppInfo)->m_Addr = *pAddr; + (*ppInfo)->m_DataSize = DataSize; + int64 Now = time_get(); + (*ppInfo)->m_Expiry = Now + time_freq() * NET_TOKENCACHE_PACKETEXPIRY; + (*ppInfo)->m_LastTokenRequest = Now; + (*ppInfo)->m_pNext = 0; + if(pCallbackData) + { + (*ppInfo)->m_pfnCallback = pCallbackData->m_pfnCallback; + (*ppInfo)->m_pCallbackUser = pCallbackData->m_pCallbackUser; + pCallbackData->m_TrackID = (*ppInfo)->m_TrackID; + } + else + { + (*ppInfo)->m_pfnCallback = 0; + (*ppInfo)->m_pCallbackUser = 0; + } + } +} + +void CNetTokenCache::PurgeStoredPacket(int TrackID) +{ + CConnlessPacketInfo *pPrevInfo = 0; + CConnlessPacketInfo *pInfo = m_pConnlessPacketList; + while(pInfo) + { + if(pInfo->m_TrackID == TrackID) + { + // purge desired packet + CConnlessPacketInfo *pNext = pInfo->m_pNext; + if(pPrevInfo) + pPrevInfo->m_pNext = pNext; + if(pInfo == m_pConnlessPacketList) + m_pConnlessPacketList = pNext; + delete pInfo; + + break; + } + else + { + if(pPrevInfo) + pPrevInfo = pPrevInfo->m_pNext; + else + pPrevInfo = pInfo; + pInfo = pInfo->m_pNext; + } + } +} + +TOKEN CNetTokenCache::GetToken(const NETADDR *pAddr) +{ + // traverse the list in the reverse direction + // newest caches are the best + CAddressInfo *pInfo = m_TokenCache.Last(); + while(pInfo) + { + if(net_addr_comp(&pInfo->m_Addr, pAddr, true) == 0) + return pInfo->m_Token; + pInfo = m_TokenCache.Prev(pInfo); + } + return NET_TOKEN_NONE; +} + +void CNetTokenCache::FetchToken(const NETADDR *pAddr) +{ + m_pNetBase->SendControlMsgWithToken(pAddr, NET_TOKEN_NONE, 0, NET_CTRLMSG_TOKEN, m_pTokenManager->GenerateToken(pAddr), true); +} + +void CNetTokenCache::AddToken(const NETADDR *pAddr, TOKEN Token, int TokenFLag) +{ + if(Token == NET_TOKEN_NONE) + return; + + // search the list of packets to be sent + // for this address + CConnlessPacketInfo *pPrevInfo = 0; + CConnlessPacketInfo *pInfo = m_pConnlessPacketList; + bool Found = false; + while(pInfo) + { + NETADDR NullAddr = { 0 }; + NullAddr.type = 7; // cover broadcasts + if(net_addr_comp(&pInfo->m_Addr, pAddr, true) == 0 || ((TokenFLag&NET_TOKENFLAG_ALLOWBROADCAST) && net_addr_comp(&pInfo->m_Addr, &NullAddr, false) == 0)) + { + // notify the user that the packet gets delivered + if(pInfo->m_pfnCallback) + pInfo->m_pfnCallback(pInfo->m_TrackID, pInfo->m_pCallbackUser); + m_pNetBase->SendPacketConnless(&(pInfo->m_Addr), Token, m_pTokenManager->GenerateToken(pAddr), pInfo->m_aData, pInfo->m_DataSize); + CConnlessPacketInfo *pNext = pInfo->m_pNext; + if(pPrevInfo) + pPrevInfo->m_pNext = pNext; + if(pInfo == m_pConnlessPacketList) + m_pConnlessPacketList = pNext; + delete pInfo; + pInfo = pNext; + } + else + { + if(pPrevInfo) + pPrevInfo = pPrevInfo->m_pNext; + else + pPrevInfo = pInfo; + pInfo = pInfo->m_pNext; + } + } + + // add the token + if(Found || !(TokenFLag&NET_TOKENFLAG_RESPONSEONLY)) + { + CAddressInfo Info; + Info.m_Addr = *pAddr; + Info.m_Token = Token; + Info.m_Expiry = time_get() + time_freq() * NET_TOKENCACHE_ADDRESSEXPIRY; + (*m_TokenCache.Allocate(sizeof(Info))) = Info; + } +} + +void CNetTokenCache::Update() +{ + int64 Now = time_get(); + + // drop expired address info + CAddressInfo *pAddrInfo; + while((pAddrInfo = m_TokenCache.First()) && (pAddrInfo->m_Expiry <= Now)) + m_TokenCache.PopFirst(); + + // try to fetch the token again for stored packets + CConnlessPacketInfo * pEntry = m_pConnlessPacketList; + while(pEntry) + { + if(pEntry->m_LastTokenRequest + 2*time_freq() <= Now) + { + FetchToken(&pEntry->m_Addr); + pEntry->m_LastTokenRequest = Now; + } + pEntry = pEntry->m_pNext; + } + + // drop expired packets + while(m_pConnlessPacketList && m_pConnlessPacketList->m_Expiry <= Now) + { + CConnlessPacketInfo *pNewList = m_pConnlessPacketList->m_pNext; + delete m_pConnlessPacketList; + m_pConnlessPacketList = pNewList; + } +} + diff --git a/src/engine/shared/packer.cpp b/src/engine/shared/packer.cpp new file mode 100644 index 000000000..e39cb2994 --- /dev/null +++ b/src/engine/shared/packer.cpp @@ -0,0 +1,171 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include "packer.h" +#include "compression.h" +#include "config.h" + +void CPacker::Reset() +{ + m_Error = 0; + m_pCurrent = m_aBuffer; + m_pEnd = m_pCurrent + PACKER_BUFFER_SIZE; +} + +void CPacker::AddInt(int i) +{ + if(m_Error) + return; + + // make sure that we have space enough + if(m_pEnd - m_pCurrent <= CVariableInt::MAX_BYTES_PACKED) + { + dbg_break(); + m_Error = 1; + } + else + m_pCurrent = CVariableInt::Pack(m_pCurrent, i); +} + +void CPacker::AddString(const char *pStr, int Limit) +{ + if(m_Error) + return; + + // + if(Limit > 0) + { + while(*pStr && Limit != 0) + { + *m_pCurrent++ = *pStr++; + Limit--; + + if(m_pCurrent >= m_pEnd) + { + m_Error = 1; + break; + } + } + *m_pCurrent++ = 0; + } + else + { + while(*pStr) + { + *m_pCurrent++ = *pStr++; + + if(m_pCurrent >= m_pEnd) + { + m_Error = 1; + break; + } + } + *m_pCurrent++ = 0; + } +} + +void CPacker::AddRaw(const void *pData, int Size) +{ + if(m_Error) + return; + + if(m_pCurrent+Size >= m_pEnd) + { + m_Error = 1; + return; + } + + const unsigned char *pSrc = (const unsigned char *)pData; + while(Size) + { + *m_pCurrent++ = *pSrc++; + Size--; + } +} + + +void CUnpacker::Reset(const void *pData, int Size) +{ + m_Error = 0; + m_pStart = (const unsigned char *)pData; + m_pEnd = m_pStart + Size; + m_pCurrent = m_pStart; +} + +int CUnpacker::GetInt() +{ + if(m_Error) + return 0; + + if(m_pCurrent >= m_pEnd) + { + m_Error = 1; + return 0; + } + + int i; + m_pCurrent = CVariableInt::Unpack(m_pCurrent, &i); + if(m_pCurrent > m_pEnd) + { + m_Error = 1; + return 0; + } + return i; +} + +int CUnpacker::GetIntOrDefault(int Default) +{ + if(m_Error) + { + return 0; + } + if(m_pCurrent == m_pEnd) + { + return Default; + } + return GetInt(); +} + +const char *CUnpacker::GetString(int SanitizeType) +{ + if(m_Error || m_pCurrent >= m_pEnd) + return ""; + + char *pPtr = (char *)m_pCurrent; + while(*m_pCurrent) // skip the string + { + m_pCurrent++; + if(m_pCurrent == m_pEnd) + { + m_Error = 1;; + return ""; + } + } + m_pCurrent++; + + // sanitize all strings + if(SanitizeType&SANITIZE) + str_sanitize(pPtr); + else if(SanitizeType&SANITIZE_CC) + str_sanitize_cc(pPtr); + return SanitizeType&SKIP_START_WHITESPACES ? str_utf8_skip_whitespaces(pPtr) : pPtr; +} + +const unsigned char *CUnpacker::GetRaw(int Size) +{ + const unsigned char *pPtr = m_pCurrent; + if(m_Error) + return 0; + + // check for nasty sizes + if(Size < 0 || m_pCurrent+Size > m_pEnd) + { + m_Error = 1; + return 0; + } + + // "unpack" the data + m_pCurrent += Size; + return pPtr; +} diff --git a/src/engine/shared/packer.h b/src/engine/shared/packer.h new file mode 100644 index 000000000..967c2e6d0 --- /dev/null +++ b/src/engine/shared/packer.h @@ -0,0 +1,52 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_PACKER_H +#define ENGINE_SHARED_PACKER_H + + + +class CPacker +{ + enum + { + PACKER_BUFFER_SIZE=1024*2 + }; + + unsigned char m_aBuffer[PACKER_BUFFER_SIZE]; + unsigned char *m_pCurrent; + unsigned char *m_pEnd; + int m_Error; +public: + void Reset(); + void AddInt(int i); + void AddString(const char *pStr, int Limit); + void AddRaw(const void *pData, int Size); + + int Size() const { return (int)(m_pCurrent-m_aBuffer); } + const unsigned char *Data() const { return m_aBuffer; } + bool Error() const { return m_Error; } +}; + +class CUnpacker +{ + const unsigned char *m_pStart; + const unsigned char *m_pCurrent; + const unsigned char *m_pEnd; + int m_Error; +public: + enum + { + SANITIZE=1, + SANITIZE_CC=2, + SKIP_START_WHITESPACES=4 + }; + + void Reset(const void *pData, int Size); + int GetInt(); + int GetIntOrDefault(int Default); + const char *GetString(int SanitizeType = SANITIZE); + const unsigned char *GetRaw(int Size); + bool Error() const { return m_Error; } +}; + +#endif diff --git a/src/engine/shared/protocol.h b/src/engine/shared/protocol.h new file mode 100644 index 000000000..33fc72ab4 --- /dev/null +++ b/src/engine/shared/protocol.h @@ -0,0 +1,108 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_PROTOCOL_H +#define ENGINE_SHARED_PROTOCOL_H + +#include + +/* + Connection diagram - How the initialization works. + + Client -> INFO -> Server + Contains version info, name, and some other info. + + Client <- MAP <- Server + Contains current map. + + Client -> READY -> Server + The client has loaded the map and is ready to go, + but the mod needs to send it's information aswell. + modc_connected is called on the client and + mods_connected is called on the server. + The client should call client_entergame when the + mod has done it's initialization. + + Client -> ENTERGAME -> Server + Tells the server to start sending snapshots. + client_entergame and server_client_enter is called. +*/ + + +enum +{ + NETMSG_NULL=0, + + // the first thing sent by the client + // contains the version info for the client + NETMSG_INFO=1, + + // sent by server + NETMSG_MAP_CHANGE, // sent when client should switch map + NETMSG_MAP_DATA, // map transfer, contains a chunk of the map file + NETMSG_SERVERINFO, + NETMSG_CON_READY, // connection is ready, client should send start info + NETMSG_SNAP, // normal snapshot, multiple parts + NETMSG_SNAPEMPTY, // empty snapshot + NETMSG_SNAPSINGLE, // ? + NETMSG_SNAPSMALL, // + NETMSG_INPUTTIMING, // reports how off the input was + NETMSG_RCON_AUTH_ON, // rcon authentication enabled + NETMSG_RCON_AUTH_OFF, // rcon authentication disabled + NETMSG_RCON_LINE, // line that should be printed to the remote console + NETMSG_RCON_CMD_ADD, + NETMSG_RCON_CMD_REM, + + NETMSG_AUTH_CHALLANGE, // + NETMSG_AUTH_RESULT, // + + // sent by client + NETMSG_READY, // + NETMSG_ENTERGAME, + NETMSG_INPUT, // contains the inputdata from the client + NETMSG_RCON_CMD, // + NETMSG_RCON_AUTH, // + NETMSG_REQUEST_MAP_DATA,// + + NETMSG_AUTH_START, // + NETMSG_AUTH_RESPONSE, // + + // sent by both + NETMSG_PING, + NETMSG_PING_REPLY, + NETMSG_ERROR, + + NETMSG_MAPLIST_ENTRY_ADD,// todo 0.8: move up + NETMSG_MAPLIST_ENTRY_REM, +}; + +// this should be revised +enum +{ + SERVER_TICK_SPEED=50, + SERVERINFO_FLAG_PASSWORD = 0x1, + SERVERINFO_FLAG_TIMESCORE = 0x2, + SERVERINFO_LEVEL_MIN=0, + SERVERINFO_LEVEL_MAX=2, + + MAX_CLIENTS=64, + MAX_PLAYERS=16, + + MAX_INPUT_SIZE=128, + MAX_SNAPSHOT_PACKSIZE=900, + + MAX_NAME_LENGTH=16, + MAX_NAME_ARRAY_SIZE=MAX_NAME_LENGTH*UTF8_BYTE_LENGTH+1, + MAX_CLAN_LENGTH=12, + MAX_CLAN_ARRAY_SIZE=MAX_CLAN_LENGTH*UTF8_BYTE_LENGTH+1, + MAX_SKIN_LENGTH=24, + MAX_SKIN_ARRAY_SIZE=MAX_SKIN_LENGTH*UTF8_BYTE_LENGTH+1, + + // message packing + MSGFLAG_VITAL=1, + MSGFLAG_FLUSH=2, + MSGFLAG_NORECORD=4, + MSGFLAG_RECORD=8, + MSGFLAG_NOSEND=16 +}; + +#endif diff --git a/src/engine/shared/ringbuffer.cpp b/src/engine/shared/ringbuffer.cpp new file mode 100644 index 000000000..a164a83e5 --- /dev/null +++ b/src/engine/shared/ringbuffer.cpp @@ -0,0 +1,194 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include "ringbuffer.h" + +CRingBufferBase::CItem *CRingBufferBase::NextBlock(CItem *pItem) +{ + if(pItem->m_pNext) + return pItem->m_pNext; + return m_pFirst; +} + +CRingBufferBase::CItem *CRingBufferBase::PrevBlock(CItem *pItem) +{ + if(pItem->m_pPrev) + return pItem->m_pPrev; + return m_pLast; +} + +CRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem) +{ + // make sure that this block and previous block is free + if(!pItem->m_Free || !pItem->m_pPrev || !pItem->m_pPrev->m_Free) + return pItem; + + // merge the blocks + pItem->m_pPrev->m_Size += pItem->m_Size; + pItem->m_pPrev->m_pNext = pItem->m_pNext; + + // fixup pointers + if(pItem->m_pNext) + pItem->m_pNext->m_pPrev = pItem->m_pPrev; + else + m_pLast = pItem->m_pPrev; + + if(pItem == m_pProduce) + m_pProduce = pItem->m_pPrev; + + if(pItem == m_pConsume) + m_pConsume = pItem->m_pPrev; + + // return the current block + return pItem->m_pPrev; +} + +void CRingBufferBase::Init(void *pMemory, int Size, int Flags) +{ + mem_zero(pMemory, Size); + m_Size = (Size)/sizeof(CItem)*sizeof(CItem); + m_pFirst = (CItem *)pMemory; + m_pFirst->m_Free = 1; + m_pFirst->m_Size = m_Size; + m_pLast = m_pFirst; + m_pProduce = m_pFirst; + m_pConsume = m_pFirst; + m_Flags = Flags; + +} + +void *CRingBufferBase::Allocate(int Size) +{ + int WantedSize = (Size+sizeof(CItem)+sizeof(CItem)-1)/sizeof(CItem)*sizeof(CItem); + CItem *pBlock = 0; + + // check if we even can fit this block + if(WantedSize > m_Size) + return 0; + + while(1) + { + // check for space + if(m_pProduce->m_Free) + { + if(m_pProduce->m_Size >= WantedSize) + pBlock = m_pProduce; + else + { + // wrap around to try to find a block + if(m_pFirst->m_Free && m_pFirst->m_Size >= WantedSize) + pBlock = m_pFirst; + } + } + + if(pBlock) + break; + else + { + // we have no block, check our policy and see what todo + if(m_Flags&FLAG_RECYCLE) + { + if(!PopFirst()) + return 0; + } + else + return 0; + } + } + + // okey, we have our block + + // split the block if needed + if(pBlock->m_Size > WantedSize+(int)sizeof(CItem)) + { + CItem *pNewItem = (CItem *)((char *)pBlock + WantedSize); + pNewItem->m_pPrev = pBlock; + pNewItem->m_pNext = pBlock->m_pNext; + if(pNewItem->m_pNext) + pNewItem->m_pNext->m_pPrev = pNewItem; + pBlock->m_pNext = pNewItem; + + pNewItem->m_Free = 1; + pNewItem->m_Size = pBlock->m_Size - WantedSize; + pBlock->m_Size = WantedSize; + + if(!pNewItem->m_pNext) + m_pLast = pNewItem; + } + + + // set next block + m_pProduce = NextBlock(pBlock); + + // set as used and return the item pointer + pBlock->m_Free = 0; + return (void *)(pBlock+1); +} + +int CRingBufferBase::PopFirst() +{ + if(m_pConsume->m_Free) + return 0; + + // set the free flag + m_pConsume->m_Free = 1; + + // previous block is also free, merge them + m_pConsume = MergeBack(m_pConsume); + + // advance the consume pointer + m_pConsume = NextBlock(m_pConsume); + while(m_pConsume->m_Free && m_pConsume != m_pProduce) + { + m_pConsume = MergeBack(m_pConsume); + m_pConsume = NextBlock(m_pConsume); + } + + // in the case that we have caught up with the produce pointer + // we might stand on a free block so merge em + MergeBack(m_pConsume); + return 1; +} + + +void *CRingBufferBase::Prev(void *pCurrent) +{ + CItem *pItem = ((CItem *)pCurrent) - 1; + + while(1) + { + pItem = PrevBlock(pItem); + if(pItem == m_pProduce) + return 0; + if(!pItem->m_Free) + return pItem+1; + } +} + +void *CRingBufferBase::Next(void *pCurrent) +{ + CItem *pItem = ((CItem *)pCurrent) - 1; + + while(1) + { + pItem = NextBlock(pItem); + if(pItem == m_pProduce) + return 0; + if(!pItem->m_Free) + return pItem+1; + } +} + +void *CRingBufferBase::First() +{ + if(m_pConsume->m_Free) + return 0; + return (void *)(m_pConsume+1); +} + +void *CRingBufferBase::Last() +{ + return Prev(m_pProduce+1); +} + diff --git a/src/engine/shared/ringbuffer.h b/src/engine/shared/ringbuffer.h new file mode 100644 index 000000000..acce2320b --- /dev/null +++ b/src/engine/shared/ringbuffer.h @@ -0,0 +1,67 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_RINGBUFFER_H +#define ENGINE_SHARED_RINGBUFFER_H + +typedef struct RINGBUFFER RINGBUFFER; + +class CRingBufferBase +{ + class CItem + { + public: + CItem *m_pPrev; + CItem *m_pNext; + int m_Free; + int m_Size; + }; + + CItem *m_pProduce; + CItem *m_pConsume; + + CItem *m_pFirst; + CItem *m_pLast; + + int m_Size; + int m_Flags; + + CItem *NextBlock(CItem *pItem); + CItem *PrevBlock(CItem *pItem); + CItem *MergeBack(CItem *pItem); +protected: + void *Allocate(int Size); + + void *Prev(void *pCurrent); + void *Next(void *pCurrent); + void *First(); + void *Last(); + + void Init(void *pMemory, int Size, int Flags); + int PopFirst(); +public: + enum + { + // Will start to destroy items to try to fit the next one + FLAG_RECYCLE=1 + }; +}; + +template +class TStaticRingBuffer : public CRingBufferBase +{ + unsigned char m_aBuffer[TSIZE]; +public: + TStaticRingBuffer() { Init(); } + + void Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); } + + T *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); } + int PopFirst() { return CRingBufferBase::PopFirst(); } + + T *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); } + T *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); } + T *First() { return (T*)CRingBufferBase::First(); } + T *Last() { return (T*)CRingBufferBase::Last(); } +}; + +#endif diff --git a/src/engine/shared/snapshot.cpp b/src/engine/shared/snapshot.cpp new file mode 100644 index 000000000..efc39a0d1 --- /dev/null +++ b/src/engine/shared/snapshot.cpp @@ -0,0 +1,682 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include + +#include "snapshot.h" +#include "compression.h" + +// CSnapshot + +const CSnapshotItem *CSnapshot::GetItem(int Index) const +{ + return (const CSnapshotItem *)(DataStart() + Offsets()[Index]); +} + +int CSnapshot::GetItemSize(int Index) const +{ + if(Index == m_NumItems-1) + return (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem); + return (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem); +} + +int CSnapshot::GetItemIndex(int Key) const +{ + plain_range_sorted Keys(SortedKeys(), SortedKeys() + m_NumItems); + plain_range_sorted r = ::find_binary(Keys, Key); + + if(r.empty()) + return -1; + + int Index = &r.front() - SortedKeys(); + if(GetItem(Index)->Key() != Key) + return -1; // deleted + return Index; +} + +void CSnapshot::InvalidateItem(int Index) +{ + ((CSnapshotItem *)(DataStart() + Offsets()[Index]))->Invalidate(); +} + +int CSnapshot::Serialize(char *pDstData) const +{ + int *pData = (int*)pDstData; + pData[0] = m_DataSize; + pData[1] = m_NumItems; + + mem_copy(pData+2, Offsets(), sizeof(int)*m_NumItems); + mem_copy(pData+2+m_NumItems, DataStart(), m_DataSize); + + return sizeof(int) * (2 + m_NumItems) + m_DataSize; +} + +int CSnapshot::Crc() const +{ + int Crc = 0; + + for(int i = 0; i < m_NumItems; i++) + { + const CSnapshotItem *pItem = GetItem(i); + int Size = GetItemSize(i); + + for(int b = 0; b < Size/4; b++) + Crc += pItem->Data()[b]; + } + return Crc; +} + +void CSnapshot::DebugDump() const +{ + dbg_msg("snapshot", "data_size=%d num_items=%d", m_DataSize, m_NumItems); + for(int i = 0; i < m_NumItems; i++) + { + const CSnapshotItem *pItem = GetItem(i); + int Size = GetItemSize(i); + dbg_msg("snapshot", "\ttype=%d id=%d", pItem->Type(), pItem->ID()); + for(int b = 0; b < Size/4; b++) + dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, pItem->Data()[b], pItem->Data()[b]); + } +} + + +// CSnapshotDelta + +struct CItemList +{ + int m_Num; + int m_aKeys[64]; + int m_aIndex[64]; +}; + +enum +{ + HASHLIST_SIZE = 256, +}; + +static void GenerateHash(CItemList *pHashlist, const CSnapshot *pSnapshot) +{ + for(int i = 0; i < HASHLIST_SIZE; i++) + pHashlist[i].m_Num = 0; + + for(int i = 0; i < pSnapshot->NumItems(); i++) + { + int Key = pSnapshot->GetItem(i)->Key(); + int HashID = ((Key>>12)&0xf0) | (Key&0xf); + if(pHashlist[HashID].m_Num != 64) + { + pHashlist[HashID].m_aIndex[pHashlist[HashID].m_Num] = i; + pHashlist[HashID].m_aKeys[pHashlist[HashID].m_Num] = Key; + pHashlist[HashID].m_Num++; + } + } +} + +static int GetItemIndexHashed(int Key, const CItemList *pHashlist) +{ + int HashID = ((Key>>12)&0xf0) | (Key&0xf); + for(int i = 0; i < pHashlist[HashID].m_Num; i++) + { + if(pHashlist[HashID].m_aKeys[i] == Key) + return pHashlist[HashID].m_aIndex[i]; + } + + return -1; +} + +static int DiffItem(const int *pPast, const int *pCurrent, int *pOut, int Size) +{ + int Needed = 0; + while(Size) + { + *pOut = *pCurrent-*pPast; + Needed |= *pOut; + pOut++; + pPast++; + pCurrent++; + Size--; + } + + return Needed; +} + +static void UndiffItem(const int *pPast, const int *pDiff, int *pOut, int Size, int *pDataRate) +{ + while(Size) + { + *pOut = *pPast+*pDiff; + + if(*pDiff == 0) + *pDataRate += 1; + else + { + unsigned char aBuf[CVariableInt::MAX_BYTES_PACKED]; + unsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff); + *pDataRate += (int)(pEnd - (unsigned char*)aBuf) * 8; + } + + pOut++; + pPast++; + pDiff++; + Size--; + } +} + +CSnapshotDelta::CSnapshotDelta() +{ + mem_zero(m_aItemSizes, sizeof(m_aItemSizes)); + mem_zero(m_aSnapshotDataRate, sizeof(m_aSnapshotDataRate)); + mem_zero(m_aSnapshotDataUpdates, sizeof(m_aSnapshotDataUpdates)); + mem_zero(&m_Empty, sizeof(m_Empty)); +} + +void CSnapshotDelta::SetStaticsize(int ItemType, int Size) +{ + if(ItemType < 0 || ItemType >= MAX_NETOBJSIZES) + return; + m_aItemSizes[ItemType] = Size; +} + +const CSnapshotDelta::CData *CSnapshotDelta::EmptyDelta() const +{ + return &m_Empty; +} + +// TODO: OPT: this should be made much faster +int CSnapshotDelta::CreateDelta(const CSnapshot *pFrom, CSnapshot *pTo, void *pDstData) +{ + CData *pDelta = (CData *)pDstData; + int *pData = (int *)pDelta->m_pData; + int i, ItemSize, PastIndex; + const CSnapshotItem *pFromItem; + const CSnapshotItem *pCurItem; + const CSnapshotItem *pPastItem; + int SizeCount = 0; + + pDelta->m_NumDeletedItems = 0; + pDelta->m_NumUpdateItems = 0; + pDelta->m_NumTempItems = 0; + + CItemList Hashlist[HASHLIST_SIZE]; + GenerateHash(Hashlist, pTo); + + // pack deleted stuff + for(i = 0; i < pFrom->NumItems(); i++) + { + pFromItem = pFrom->GetItem(i); + if(GetItemIndexHashed(pFromItem->Key(), Hashlist) == -1) + { + // deleted + pDelta->m_NumDeletedItems++; + *pData = pFromItem->Key(); + pData++; + } + } + + GenerateHash(Hashlist, pFrom); + int aPastIndecies[1024]; + + // fetch previous indices + // we do this as a separate pass because it helps the cache + const int NumItems = pTo->NumItems(); + for(i = 0; i < NumItems; i++) + { + pCurItem = pTo->GetItem(i); // O(1) .. O(n) + aPastIndecies[i] = GetItemIndexHashed(pCurItem->Key(), Hashlist); // O(n) .. O(n^n) + } + + for(i = 0; i < NumItems; i++) + { + // do delta + ItemSize = pTo->GetItemSize(i); // O(1) .. O(n) + pCurItem = pTo->GetItem(i); // O(1) .. O(n) + PastIndex = aPastIndecies[i]; + + bool IncludeSize = pCurItem->Type() >= MAX_NETOBJSIZES || !m_aItemSizes[pCurItem->Type()]; + + if(PastIndex != -1) + { + int *pItemDataDst = pData+3; + + pPastItem = pFrom->GetItem(PastIndex); + + if(!IncludeSize) + pItemDataDst = pData+2; + + if(DiffItem(pPastItem->Data(), (int*)pCurItem->Data(), pItemDataDst, ItemSize/4)) + { + + *pData++ = pCurItem->Type(); + *pData++ = pCurItem->ID(); + if(IncludeSize) + *pData++ = ItemSize/4; + pData += ItemSize/4; + pDelta->m_NumUpdateItems++; + } + } + else + { + *pData++ = pCurItem->Type(); + *pData++ = pCurItem->ID(); + if(IncludeSize) + *pData++ = ItemSize/4; + + mem_copy(pData, pCurItem->Data(), ItemSize); + SizeCount += ItemSize; + pData += ItemSize/4; + pDelta->m_NumUpdateItems++; + } + } + + if(0) + { + dbg_msg("snapshot", "%d %d %d", + pDelta->m_NumDeletedItems, + pDelta->m_NumUpdateItems, + pDelta->m_NumTempItems); + } + + /* + // TODO: pack temp stuff + + // finish + //mem_copy(pDelta->offsets, deleted, pDelta->num_deleted_items*sizeof(int)); + //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items]), update, pDelta->num_update_items*sizeof(int)); + //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items+pDelta->num_update_items]), temp, pDelta->num_temp_items*sizeof(int)); + //mem_copy(pDelta->data_start(), data, data_size); + //pDelta->data_size = data_size; + * */ + + if(!pDelta->m_NumDeletedItems && !pDelta->m_NumUpdateItems && !pDelta->m_NumTempItems) + return 0; + + return (int)((char*)pData-(char*)pDstData); +} + +static int RangeCheck(const void *pEnd, const void *pPtr, int Size) +{ + if((const char *)pPtr + Size > (const char *)pEnd) + return -1; + return 0; +} + +int CSnapshotDelta::UnpackDelta(const CSnapshot *pFrom, CSnapshot *pTo, const void *pSrcData, int DataSize) +{ + CSnapshotBuilder Builder; + const CData *pDelta = (const CData *)pSrcData; + const int *pData = (const int *)pDelta->m_pData; + const int *pEnd = (const int *)(((const char *)pSrcData + DataSize)); + + const CSnapshotItem *pFromItem; + int Keep, ItemSize; + const int *pDeleted; + int ID, Type, Key; + int FromIndex; + int *pNewData; + + Builder.Init(); + + // unpack deleted stuff + pDeleted = pData; + if(pDelta->m_NumDeletedItems < 0) + return -1; + pData += pDelta->m_NumDeletedItems; + if(pData > pEnd) + return -1; + + // copy all non deleted stuff + for(int i = 0; i < pFrom->NumItems(); i++) + { + // dbg_assert(0, "fail!"); + pFromItem = pFrom->GetItem(i); + ItemSize = pFrom->GetItemSize(i); + Keep = 1; + for(int d = 0; d < pDelta->m_NumDeletedItems; d++) + { + if(pDeleted[d] == pFromItem->Key()) + { + Keep = 0; + break; + } + } + + if(Keep) + { + // keep it + mem_copy( + Builder.NewItem(pFromItem->Type(), pFromItem->ID(), ItemSize), + pFromItem->Data(), ItemSize); + } + } + + // unpack updated stuff + for(int i = 0; i < pDelta->m_NumUpdateItems; i++) + { + if(pData+2 > pEnd) + return -1; + + Type = *pData++; + if(Type < 0 || Type > CSnapshot::MAX_TYPE) + return -3; + + ID = *pData++; + if(ID < 0 || ID > CSnapshot::MAX_ID) + return -3; + + if(Type < MAX_NETOBJSIZES && m_aItemSizes[Type]) + ItemSize = m_aItemSizes[Type]; + else + { + if(pData+1 > pEnd) + return -2; + if(*pData < 0 || *pData > INT_MAX / 4) + return -3; + ItemSize = (*pData++) * 4; + } + + if(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) return -3; + + Key = (Type<<16)|(ID&0xffff); + + // create the item if needed + pNewData = Builder.GetItemData(Key); + if(!pNewData) + pNewData = (int *)Builder.NewItem(Key>>16, Key&0xffff, ItemSize); + + //if(range_check(pEnd, pNewData, ItemSize)) return -4; + + FromIndex = pFrom->GetItemIndex(Key); + if(FromIndex != -1) + { + // we got an update so we need to apply the diff + UndiffItem(pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize / 4, &m_aSnapshotDataRate[Type]); + m_aSnapshotDataUpdates[Type]++; + } + else // no previous, just copy the pData + { + mem_copy(pNewData, pData, ItemSize); + m_aSnapshotDataRate[Type] += ItemSize * 8; + m_aSnapshotDataUpdates[Type]++; + } + + pData += ItemSize/4; + } + + // finish up + return Builder.Finish(pTo); +} + + +// CSnapshotStorage + +CSnapshotStorage::~CSnapshotStorage() +{ + PurgeAll(); +} + +void CSnapshotStorage::Init() +{ + m_pFirst = 0; + m_pLast = 0; +} + +void CSnapshotStorage::PurgeAll() +{ + CHolder *pHolder = m_pFirst; + + while(pHolder) + { + CHolder *pNext = pHolder->m_pNext; + mem_free(pHolder); + pHolder = pNext; + } + + // no more snapshots in storage + m_pFirst = 0; + m_pLast = 0; +} + +void CSnapshotStorage::PurgeUntil(int Tick) +{ + CHolder *pHolder = m_pFirst; + + while(pHolder) + { + CHolder *pNext = pHolder->m_pNext; + if(pHolder->m_Tick >= Tick) + return; // no more to remove + mem_free(pHolder); + + // did we come to the end of the list? + if (!pNext) + break; + + m_pFirst = pNext; + pNext->m_pPrev = 0x0; + + pHolder = pNext; + } + + // no more snapshots in storage + m_pFirst = 0; + m_pLast = 0; +} + +void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, const void *pData, bool CreateAlt) +{ + // allocate memory for holder + snapshot_data + int TotalSize = sizeof(CHolder)+DataSize; + + if(CreateAlt) + TotalSize += DataSize; + + CHolder *pHolder = (CHolder *)mem_alloc(TotalSize); + + // set data + pHolder->m_Tick = Tick; + pHolder->m_Tagtime = Tagtime; + pHolder->m_SnapSize = DataSize; + pHolder->m_pSnap = (CSnapshot*)(pHolder+1); + mem_copy(pHolder->m_pSnap, pData, DataSize); + + if(CreateAlt) // create alternative if wanted + { + pHolder->m_pAltSnap = (CSnapshot*)(((char *)pHolder->m_pSnap) + DataSize); + mem_copy(pHolder->m_pAltSnap, pData, DataSize); + } + else + pHolder->m_pAltSnap = 0; + + + // link + pHolder->m_pNext = 0; + pHolder->m_pPrev = m_pLast; + if(m_pLast) + m_pLast->m_pNext = pHolder; + else + m_pFirst = pHolder; + m_pLast = pHolder; +} + +int CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData) const +{ + CHolder *pHolder = m_pFirst; + + while(pHolder) + { + if(pHolder->m_Tick == Tick) + { + if(pTagtime) + *pTagtime = pHolder->m_Tagtime; + if(ppData) + *ppData = pHolder->m_pSnap; + if(ppAltData) + *ppAltData = pHolder->m_pAltSnap; + return pHolder->m_SnapSize; + } + + pHolder = pHolder->m_pNext; + } + + return -1; +} + +// CSnapshotBuilder + +void CSnapshotBuilder::Init() +{ + m_DataSize = 0; + m_NumItems = 0; +} + +void CSnapshotBuilder::Init(const CSnapshot *pSnapshot) +{ + if(pSnapshot->m_DataSize + sizeof(CSnapshot) + pSnapshot->m_NumItems * sizeof(int)*2 > CSnapshot::MAX_SIZE || pSnapshot->m_NumItems > MAX_ITEMS) + { + // key and offset per item + dbg_assert(m_DataSize + sizeof(CSnapshot) + m_NumItems * sizeof(int)*2 < CSnapshot::MAX_SIZE, "too much data"); + dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); + dbg_msg("snapshot", "invalid snapshot"); // remove me + m_DataSize = 0; + m_NumItems = 0; + return; + } + + m_DataSize = pSnapshot->m_DataSize; + m_NumItems = pSnapshot->m_NumItems; + mem_copy(m_aOffsets, pSnapshot->Offsets(), sizeof(int)*m_NumItems); + mem_copy(m_aData, pSnapshot->DataStart(), m_DataSize); +} + +bool CSnapshotBuilder::UnserializeSnap(const char *pSrcData, int SrcSize) +{ + m_DataSize = 0; + m_NumItems = 0; + + const int *pData = (const int*)pSrcData; + if(SrcSize < (int)sizeof(int)*2) + return false; + + int DataSize = pData[0]; + int NumItems = pData[1]; + int CompleteSize = DataSize + sizeof(int) * (2 + NumItems); + int NewSnapSize = DataSize + sizeof(CSnapshot) + NumItems * sizeof(int)*2; + if(NewSnapSize > CSnapshot::MAX_SIZE || NumItems > MAX_ITEMS || CompleteSize != SrcSize) + return false; + + // check offsets + const int *pOffsets = pData+2; + int LastOffset = DataSize; + for(int i = NumItems-1; i >= 0; i--) + { + int ItemSize = LastOffset - pOffsets[i]; + LastOffset = pOffsets[i]; + if(pOffsets[i] < 0 || ItemSize < (int)sizeof(CSnapshotItem)) + return false; + } + + m_DataSize = DataSize; + m_NumItems = NumItems; + mem_copy(m_aOffsets, pOffsets, sizeof(int)*m_NumItems); + mem_copy(m_aData, pOffsets+m_NumItems, m_DataSize); + return true; +} + +CSnapshotItem *CSnapshotBuilder::GetItem(int Index) const +{ + return (CSnapshotItem *)&(m_aData[m_aOffsets[Index]]); +} + +int *CSnapshotBuilder::GetItemData(int Key) const +{ + for(int i = 0; i < m_NumItems; i++) + { + if(GetItem(i)->Key() == Key) + return GetItem(i)->Data(); + } + return 0; +} + +int CSnapshotBuilder::Finish(void *pSnapdata) +{ + // flattern and make the snapshot + CSnapshot *pSnap = (CSnapshot *)pSnapdata; + int OffsetSize = sizeof(int)*m_NumItems; + int KeySize = sizeof(int)*m_NumItems; + pSnap->m_DataSize = m_DataSize; + pSnap->m_NumItems = m_NumItems; + + const int NumItems = m_NumItems; + for(int i = 0; i < NumItems; i++) + { + pSnap->SortedKeys()[i] = GetItem(i)->Key(); + } + + // get full item sizes + int aItemSizes[CSnapshotBuilder::MAX_ITEMS]; + + for(int i = 0; i < NumItems; i++) + { + if(i < NumItems - 1) + { + aItemSizes[i] = m_aOffsets[i+1] - m_aOffsets[i]; + } + else + { + aItemSizes[i] = m_DataSize - m_aOffsets[i]; + } + } + + // bubble sort by keys + bool Sorting = true; + while(Sorting) + { + Sorting = false; + + for(int i = 1; i < NumItems; i++) + { + if(pSnap->SortedKeys()[i-1] > pSnap->SortedKeys()[i]) + { + Sorting = true; + std::swap(pSnap->SortedKeys()[i], pSnap->SortedKeys()[i-1]); + std::swap(m_aOffsets[i], m_aOffsets[i-1]); + std::swap(aItemSizes[i], aItemSizes[i-1]); + } + } + } + + // copy sorted items + int OffsetCur = 0; + for(int i = 0; i < NumItems; i++) + { + pSnap->Offsets()[i] = OffsetCur; + mem_copy(pSnap->DataStart()+OffsetCur, m_aData + m_aOffsets[i], aItemSizes[i]); + OffsetCur += aItemSizes[i]; + } + + return sizeof(CSnapshot) + KeySize + OffsetSize + m_DataSize; +} + +void *CSnapshotBuilder::NewItem(int Type, int ID, int Size) +{ + if(m_DataSize + sizeof(CSnapshot) + sizeof(CSnapshotItem) + Size + (m_NumItems+1) * sizeof(int)*2 >= CSnapshot::MAX_SIZE || + m_NumItems+1 >= MAX_ITEMS) + { + // key and offset per item + dbg_assert(m_DataSize + sizeof(CSnapshot) + m_NumItems * sizeof(int)*2 < CSnapshot::MAX_SIZE, "too much data"); + dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); + return 0; + } + + CSnapshotItem *pObj = (CSnapshotItem *)(m_aData + m_DataSize); + + mem_zero(pObj, sizeof(CSnapshotItem) + Size); + pObj->SetKey(Type, ID); + m_aOffsets[m_NumItems] = m_DataSize; + m_DataSize += sizeof(CSnapshotItem) + Size; + m_NumItems++; + + return pObj->Data(); +} diff --git a/src/engine/shared/snapshot.h b/src/engine/shared/snapshot.h new file mode 100644 index 000000000..837614e46 --- /dev/null +++ b/src/engine/shared/snapshot.h @@ -0,0 +1,153 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_SNAPSHOT_H +#define ENGINE_SHARED_SNAPSHOT_H + +#include + +// CSnapshot + +class CSnapshotItem +{ + friend class CSnapshotBuilder; + int m_TypeAndID; + + int *Data() { return (int *)(this+1); } + +public: + const int *Data() const { return (int *)(this+1); } + int Type() const { return m_TypeAndID>>16; } + int ID() const { return m_TypeAndID&0xffff; } + int Key() const { return m_TypeAndID; } + void SetKey(int Type, int ID) { m_TypeAndID = (Type<<16)|(ID&0xffff); } + void Invalidate() { m_TypeAndID = -1; } +}; + + +class CSnapshot +{ + friend class CSnapshotBuilder; + int m_DataSize; + int m_NumItems; + + int *SortedKeys() const { return (int *)(this+1); } + int *Offsets() const { return (int *)(SortedKeys()+m_NumItems); } + char *DataStart() const { return (char*)(Offsets()+m_NumItems); } + +public: + enum + { + MAX_TYPE = 0x7fff, + MAX_ID = 0xffff, + MAX_PARTS = 64, + MAX_SIZE = MAX_PARTS*1024 + }; + + void Clear() { m_DataSize = 0; m_NumItems = 0; } + int NumItems() const { return m_NumItems; } + const CSnapshotItem *GetItem(int Index) const; + int GetItemSize(int Index) const; + int GetItemIndex(int Key) const; + void InvalidateItem(int Index); + + int Serialize(char *pDstData) const; + + int Crc() const; + void DebugDump() const; +}; + + +// CSnapshotDelta + +class CSnapshotDelta +{ +public: + class CData + { + public: + int m_NumDeletedItems; + int m_NumUpdateItems; + int m_NumTempItems; // needed? + int m_pData[1]; + }; + +private: + enum + { + MAX_NETOBJSIZES=64 + }; + short m_aItemSizes[MAX_NETOBJSIZES]; + int m_aSnapshotDataRate[CSnapshot::MAX_TYPE + 1]; + int m_aSnapshotDataUpdates[CSnapshot::MAX_TYPE + 1]; + CData m_Empty; + +public: + CSnapshotDelta(); + int GetDataRate(int Index) const { return m_aSnapshotDataRate[Index]; } + int GetDataUpdates(int Index) const { return m_aSnapshotDataUpdates[Index]; } + void SetStaticsize(int ItemType, int Size); + const CData *EmptyDelta() const; + int CreateDelta(const class CSnapshot *pFrom, class CSnapshot *pTo, void *pDstData); + int UnpackDelta(const class CSnapshot *pFrom, class CSnapshot *pTo, const void *pSrcData, int DataSize); +}; + + +// CSnapshotStorage + +class CSnapshotStorage +{ +public: + class CHolder + { + public: + CHolder *m_pPrev; + CHolder *m_pNext; + + int64 m_Tagtime; + int m_Tick; + + int m_SnapSize; + CSnapshot *m_pSnap; + CSnapshot *m_pAltSnap; + }; + + + CHolder *m_pFirst; + CHolder *m_pLast; + + ~CSnapshotStorage(); + void Init(); + void PurgeAll(); + void PurgeUntil(int Tick); + void Add(int Tick, int64 Tagtime, int DataSize, const void *pData, bool CreateAlt); + int Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData) const; +}; + +class CSnapshotBuilder +{ + enum + { + MAX_ITEMS = 1024 + }; + + char m_aData[CSnapshot::MAX_SIZE]; + int m_DataSize; + + int m_aOffsets[MAX_ITEMS]; + int m_NumItems; + +public: + void Init(); + void Init(const CSnapshot *pSnapshot); + bool UnserializeSnap(const char *pSrcData, int SrcSize); + + void *NewItem(int Type, int ID, int Size); + + CSnapshotItem *GetItem(int Index) const; + int *GetItemData(int Key) const; + + int Finish(void *pSnapdata); +}; + + +#endif // ENGINE_SNAPSHOT_H diff --git a/src/engine/shared/storage.cpp b/src/engine/shared/storage.cpp new file mode 100644 index 000000000..993f58bf6 --- /dev/null +++ b/src/engine/shared/storage.cpp @@ -0,0 +1,634 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include +#include "linereader.h" +#include + +// compiled-in data-dir path +#define DATA_DIR "data" + +class CStorage : public IStorage +{ +public: + enum + { + MAX_PATHS = 16 + }; + + char m_aaStoragePaths[MAX_PATHS][IO_MAX_PATH_LENGTH]; + int m_NumPaths; + char m_aDataDir[IO_MAX_PATH_LENGTH]; + char m_aUserDir[IO_MAX_PATH_LENGTH]; + char m_aCurrentDir[IO_MAX_PATH_LENGTH]; + char m_aAppDir[IO_MAX_PATH_LENGTH]; + + CStorage() + { + mem_zero(m_aaStoragePaths, sizeof(m_aaStoragePaths)); + m_NumPaths = 0; + m_aDataDir[0] = 0; + m_aUserDir[0] = 0; + m_aCurrentDir[0] = 0; + m_aAppDir[0] = 0; + } + + int Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) + { + // get userdir + fs_storage_path(pApplicationName, m_aUserDir, sizeof(m_aUserDir)); + + // get appdir + FindAppDir(ppArguments[0]); + + // get datadir + FindDataDir(); + + // get currentdir + fs_getcwd(m_aCurrentDir, sizeof(m_aCurrentDir)); + + // load paths from storage.cfg + LoadPaths(); + + if(!m_NumPaths) + { + dbg_msg("storage", "using standard paths"); + AddDefaultPaths(); + } + + // add save directories + if(StorageType != STORAGETYPE_BASIC) + { + if(m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir_recursive(m_aaStoragePaths[TYPE_SAVE]))) + { + char aPath[IO_MAX_PATH_LENGTH]; + if(StorageType == STORAGETYPE_CLIENT) + { + fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "skins", aPath, sizeof(aPath))); + } + fs_makedir(GetPath(TYPE_SAVE, "dumps", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "demos", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "demos/auto", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "configs", aPath, sizeof(aPath))); + } + else + { + dbg_msg("storage", "unable to create save directory"); + return 1; + } + } + + return m_NumPaths ? 0 : 1; + } + + void LoadPaths() + { + // check current directory + IOHANDLE File = io_open("storage.cfg", IOFLAG_READ | IOFLAG_SKIP_BOM); + if(!File) + { + // check usable path in argv[0] + char aBuffer[IO_MAX_PATH_LENGTH]; + str_copy(aBuffer, m_aAppDir, sizeof(aBuffer)); + str_append(aBuffer, "/storage.cfg", sizeof(aBuffer)); + File = io_open(aBuffer, IOFLAG_READ | IOFLAG_SKIP_BOM); + if(!File) + { + dbg_msg("storage", "couldn't open storage.cfg"); + return; + } + } + + CLineReader LineReader; + LineReader.Init(File); + const char *pLine; + while((pLine = LineReader.Get())) + { + const char *pLineWithoutPrefix = str_startswith(pLine, "add_path "); + if(pLineWithoutPrefix) + { + AddPath(pLineWithoutPrefix); + } + } + + io_close(File); + + if(!m_NumPaths) + dbg_msg("storage", "no paths found in storage.cfg"); + } + + void AddDefaultPaths() + { + AddPath("$USERDIR"); + AddPath("$DATADIR"); + AddPath("$CURRENTDIR"); + AddPath("$APPDIR"); + } + + bool IsDuplicatePath(const char *pPath) + { + for(int i = 0; i < m_NumPaths; ++i) + { + if(!str_comp(m_aaStoragePaths[i], pPath)) + return true; + } + return false; + } + + void AddPath(const char *pPath) + { + if(m_NumPaths >= MAX_PATHS || !pPath[0]) + return; + + if(!str_comp(pPath, "$USERDIR")) + { + if(m_aUserDir[0]) + { + if(!IsDuplicatePath(m_aUserDir)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aUserDir, IO_MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$USERDIR' ('%s')", m_aUserDir); + } + else + dbg_msg("storage", "skipping duplicate path '$USERDIR' ('%s')", m_aUserDir); + } + } + else if(!str_comp(pPath, "$DATADIR")) + { + if(m_aDataDir[0]) + { + if(!IsDuplicatePath(m_aDataDir)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aDataDir, IO_MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$DATADIR' ('%s')", m_aDataDir); + } + else + dbg_msg("storage", "skipping duplicate path '$DATADIR' ('%s')", m_aDataDir); + } + } + else if(!str_comp(pPath, "$CURRENTDIR")) + { + if(m_aCurrentDir[0]) + { + if(!IsDuplicatePath(m_aCurrentDir)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aCurrentDir, IO_MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$CURRENTDIR' ('%s')", m_aCurrentDir); + } + else + dbg_msg("storage", "skipping duplicate path '$CURRENTDIR' ('%s')", m_aCurrentDir); + } + } + else if(!str_comp(pPath, "$APPDIR")) + { + if(m_aAppDir[0]) + { + if(!IsDuplicatePath(m_aAppDir)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aAppDir, IO_MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$APPDIR' ('%s')", m_aAppDir); + } + else + dbg_msg("storage", "skipping duplicate path '$APPDIR' ('%s')", m_aAppDir); + } + } + else + { + if(fs_is_dir(pPath)) + { + if(!IsDuplicatePath(pPath)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], pPath, IO_MAX_PATH_LENGTH); + dbg_msg("storage", "added path '%s'", pPath); + } + else + dbg_msg("storage", "skipping duplicate path '%s'", pPath); + } + } + } + + void FindAppDir(const char *pArgv0) + { + // check for usable path in argv[0] + unsigned int Pos = ~0U; + for(unsigned i = 0; pArgv0[i]; ++i) + if(pArgv0[i] == '/' || pArgv0[i] == '\\') + Pos = i; + + if(Pos < IO_MAX_PATH_LENGTH) + { + str_copy(m_aAppDir, pArgv0, Pos+1); + if(!fs_is_dir(m_aAppDir)) + m_aAppDir[0] = 0; + } + } + + void FindDataDir() + { + // 1) use data-dir in PWD if present + if(fs_is_dir("data/mapres")) + { + str_copy(m_aDataDir, "data", sizeof(m_aDataDir)); + return; + } + + // 2) use compiled-in data-dir if present + if(fs_is_dir(DATA_DIR "/mapres")) + { + str_copy(m_aDataDir, DATA_DIR, sizeof(m_aDataDir)); + return; + } + + // 3) check for usable path in argv[0] + { + char aBaseDir[IO_MAX_PATH_LENGTH]; + str_copy(aBaseDir, m_aAppDir, sizeof(aBaseDir)); + str_format(m_aDataDir, sizeof(m_aDataDir), "%s/data", aBaseDir); + str_append(aBaseDir, "/data/mapres", sizeof(aBaseDir)); + + if(fs_is_dir(aBaseDir)) + return; + else + m_aDataDir[0] = 0; + } + + #if defined(CONF_FAMILY_UNIX) + // 4) check for all default locations + { + const char *aDirs[] = { + "/usr/share/teeworlds/data", + "/usr/share/games/teeworlds/data", + "/usr/local/share/teeworlds/data", + "/usr/local/share/games/teeworlds/data", + "/usr/pkg/share/teeworlds/data", + "/usr/pkg/share/games/teeworlds/data", + "/opt/teeworlds/data" + }; + const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); + + int i; + for (i = 0; i < DirsCount; i++) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s/mapres", aDirs[i]); + if(fs_is_dir(aBuf)) + { + str_copy(m_aDataDir, aDirs[i], sizeof(m_aDataDir)); + return; + } + } + } + #endif + + // no data-dir found + dbg_msg("storage", "warning no data directory found"); + } + + virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) + { + char aBuffer[IO_MAX_PATH_LENGTH]; + if(Type == TYPE_ALL) + { + // list all available directories + for(int i = 0; i < m_NumPaths; ++i) + fs_listdir(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser); + } + else if(Type >= 0 && Type < m_NumPaths) + { + // list wanted directory + fs_listdir(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser); + } + } + + virtual void ListDirectoryFileInfo(int Type, const char *pPath, FS_LISTDIR_CALLBACK_FILEINFO pfnCallback, void *pUser) + { + char aBuffer[IO_MAX_PATH_LENGTH]; + if(Type == TYPE_ALL) + { + // list all available directories + for(int i = 0; i < m_NumPaths; ++i) + fs_listdir_fileinfo(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser); + } + else if(Type >= 0 && Type < m_NumPaths) + { + // list wanted directory + fs_listdir_fileinfo(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser); + } + } + + const char *GetPath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) + { + str_format(pBuffer, BufferSize, "%s%s%s", m_aaStoragePaths[Type], !m_aaStoragePaths[Type][0] ? "" : "/", pDir); + return pBuffer; + } + + // Open a file. This checks that the path appears to be a subdirectory + // of one of the storage paths. + virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0, FCheckCallback pfnCheckCB = 0, const void *pCheckCBData = 0) + { + char aBuffer[IO_MAX_PATH_LENGTH]; + if(!pBuffer) + { + pBuffer = aBuffer; + BufferSize = sizeof(aBuffer); + } + + // Check whether the path contains '..' (parent directory) paths. We'd + // normally still have to check whether it is an absolute path + // (starts with a path separator (or a drive name on windows)), + // but since we concatenate this path with another path later + // on, this can't become absolute. + // + // E. g. "/etc/passwd" => "/path/to/storage//etc/passwd", which + // is safe. + if(str_path_unsafe(pFilename) != 0) + { + dbg_msg("storage", "refusing to open path which looks like it could escape those specified in 'storage.cfg': %s", pFilename); + return 0; + } + + // open file + if(Flags&IOFLAG_WRITE) + { + return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags); + } + else + { + IOHANDLE Handle = 0; + int LB = 0, UB = m_NumPaths; // check all available directories + + if(Type >= 0 && Type < m_NumPaths) // check wanted directory + { + LB = Type; + UB = Type + 1; + } + else + dbg_assert(Type == TYPE_ALL, "invalid storage type"); + + for(int i = LB; i < UB; ++i) + { + Handle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags); + if(Handle) + { + // do an additional check on the file + if(pfnCheckCB && !pfnCheckCB(Handle, pCheckCBData)) + { + io_close(Handle); + Handle = 0; + } + else + return Handle; + } + } + } + + pBuffer[0] = 0; + return 0; + } + + bool ReadFile(const char *pFilename, int Type, void **ppResult, unsigned *pResultLen) + { + IOHANDLE File = OpenFile(pFilename, IOFLAG_READ, Type); + *ppResult = 0; + *pResultLen = 0; + if(!File) + { + return true; + } + io_read_all(File, ppResult, pResultLen); + io_close(File); + return false; + } + + char *ReadFileStr(const char *pFilename, int Type) + { + IOHANDLE File = OpenFile(pFilename, IOFLAG_READ | IOFLAG_SKIP_BOM, Type); + if(!File) + { + return 0; + } + char *pResult = io_read_all_str(File); + io_close(File); + return pResult; + } + + struct CFindCBData + { + CStorage *m_pStorage; + const char *m_pFilename; + const char *m_pPath; + char *m_pBuffer; + int m_BufferSize; + const SHA256_DIGEST *m_pWantedSha256; + unsigned m_WantedCrc; + unsigned m_WantedSize; + bool m_CheckHashAndSize; + }; + + static int FindFileCallback(const char *pName, int IsDir, int Type, void *pUser) + { + CFindCBData Data = *static_cast(pUser); + if(IsDir) + { + if(pName[0] == '.') + return 0; + + // search within the folder + char aBuf[IO_MAX_PATH_LENGTH]; + char aPath[IO_MAX_PATH_LENGTH]; + str_format(aPath, sizeof(aPath), "%s/%s", Data.m_pPath, pName); + Data.m_pPath = aPath; + fs_listdir(Data.m_pStorage->GetPath(Type, aPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data); + if(Data.m_pBuffer[0]) + return 1; + } + else if(!str_comp(pName, Data.m_pFilename)) + { + // found the file + str_format(Data.m_pBuffer, Data.m_BufferSize, "%s/%s", Data.m_pPath, Data.m_pFilename); + + if(Data.m_CheckHashAndSize) + { + // check crc and size + SHA256_DIGEST Sha256; + unsigned Crc = 0; + unsigned Size = 0; + if(!Data.m_pStorage->GetHashAndSize(Data.m_pBuffer, Type, &Sha256, &Crc, &Size) || (Data.m_pWantedSha256 && Sha256 != *Data.m_pWantedSha256) || Crc != Data.m_WantedCrc || Size != Data.m_WantedSize) + { + Data.m_pBuffer[0] = 0; + return 0; + } + } + + return 1; + } + + return 0; + } + + bool FindFileImpl(int Type, CFindCBData *pCBData) + { + if(pCBData->m_BufferSize < 1) + return false; + + pCBData->m_pBuffer[0] = 0; + + char aBuf[IO_MAX_PATH_LENGTH]; + + if(Type == TYPE_ALL) + { + // search within all available directories + for(int i = 0; i < m_NumPaths; ++i) + { + fs_listdir(GetPath(i, pCBData->m_pPath, aBuf, sizeof(aBuf)), FindFileCallback, i, pCBData); + if(pCBData->m_pBuffer[0]) + return true; + } + } + else if(Type >= 0 && Type < m_NumPaths) + { + // search within wanted directory + fs_listdir(GetPath(Type, pCBData->m_pPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, pCBData); + } + + return pCBData->m_pBuffer[0] != 0; + } + + virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) + { + CFindCBData Data; + Data.m_pStorage = this; + Data.m_pFilename = pFilename; + Data.m_pPath = pPath; + Data.m_pBuffer = pBuffer; + Data.m_BufferSize = BufferSize; + Data.m_pWantedSha256 = 0; + Data.m_WantedCrc = 0; + Data.m_WantedSize = 0; + Data.m_CheckHashAndSize = false; + return FindFileImpl(Type, &Data); + } + + virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize, const SHA256_DIGEST *pWantedSha256, unsigned WantedCrc, unsigned WantedSize) + { + CFindCBData Data; + Data.m_pStorage = this; + Data.m_pFilename = pFilename; + Data.m_pPath = pPath; + Data.m_pBuffer = pBuffer; + Data.m_BufferSize = BufferSize; + Data.m_pWantedSha256 = pWantedSha256; + Data.m_WantedCrc = WantedCrc; + Data.m_WantedSize = WantedSize; + Data.m_CheckHashAndSize = true; + return FindFileImpl(Type, &Data); + } + + virtual bool RemoveFile(const char *pFilename, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + + char aBuffer[IO_MAX_PATH_LENGTH]; + return !fs_remove(GetPath(Type, pFilename, aBuffer, sizeof(aBuffer))); + } + + virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + char aOldBuffer[IO_MAX_PATH_LENGTH]; + char aNewBuffer[IO_MAX_PATH_LENGTH]; + return !fs_rename(GetPath(Type, pOldFilename, aOldBuffer, sizeof(aOldBuffer)), GetPath(Type, pNewFilename, aNewBuffer, sizeof (aNewBuffer))); + } + + virtual bool CreateFolder(const char *pFoldername, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + + char aBuffer[IO_MAX_PATH_LENGTH]; + return !fs_makedir(GetPath(Type, pFoldername, aBuffer, sizeof(aBuffer))); + } + + virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) + { + if(Type < 0 || Type >= m_NumPaths) + { + if(BufferSize > 0) + pBuffer[0] = 0; + return; + } + + GetPath(Type, pDir, pBuffer, BufferSize); + } + + virtual bool GetHashAndSize(const char *pFilename, int StorageType, SHA256_DIGEST *pSha256, unsigned *pCrc, unsigned *pSize) + { + IOHANDLE File = OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!File) + return false; + + // get hash and size + SHA256_CTX Sha256Ctx; + sha256_init(&Sha256Ctx); + unsigned Crc = 0; + unsigned Size = 0; + unsigned char aBuffer[64*1024]; + while(1) + { + unsigned Bytes = io_read(File, aBuffer, sizeof(aBuffer)); + if(Bytes <= 0) + break; + sha256_update(&Sha256Ctx, aBuffer, Bytes); + Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention + Size += Bytes; + } + + io_close(File); + + *pSha256 = sha256_finish(&Sha256Ctx); + *pCrc = Crc; + *pSize = Size; + return true; + } + + virtual bool GetFileTime(const char *pFilename, int StorageType, time_t *pCreated, time_t *pModified) + { + char aBuf[IO_MAX_PATH_LENGTH]; + GetCompletePath(StorageType, pFilename, aBuf, sizeof(aBuf)); + + return !fs_file_time(aBuf, pCreated, pModified); + } + + static IStorage *Create(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) + { + CStorage *p = new CStorage(); + if(p && p->Init(pApplicationName, StorageType, NumArgs, ppArguments)) + { + dbg_msg("storage", "initialisation failed"); + delete p; + p = 0; + } + return p; + } + + static IStorage *CreateTest() + { + CStorage *p = new CStorage(); + if(!p) + { + return 0; + } + p->AddPath("."); + return p; + } +}; + +IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, StorageType, NumArgs, ppArguments); } +IStorage *CreateTestStorage() { return CStorage::CreateTest(); } diff --git a/src/engine/storage.h b/src/engine/storage.h new file mode 100644 index 000000000..1d7641270 --- /dev/null +++ b/src/engine/storage.h @@ -0,0 +1,44 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_STORAGE_H +#define ENGINE_STORAGE_H + +#include +#include "kernel.h" + +class IStorage : public IInterface +{ + MACRO_INTERFACE("storage", 0) +public: + enum + { + TYPE_SAVE = 0, + TYPE_ALL = -1, + + STORAGETYPE_BASIC = 0, + STORAGETYPE_SERVER, + STORAGETYPE_CLIENT, + }; + + typedef bool(*FCheckCallback)(IOHANDLE Handle, const void *pUserData); + + virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0; + virtual void ListDirectoryFileInfo(int Type, const char *pPath, FS_LISTDIR_CALLBACK_FILEINFO pfnCallback, void *pUser) = 0; + virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0, FCheckCallback pfnCheckCB = 0, const void *pCheckCBData = 0) = 0; + virtual bool ReadFile(const char *pFilename, int Type, void **ppResult, unsigned *pResultLen) = 0; + virtual char *ReadFileStr(const char *pFilename, int Type) = 0; + virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) = 0; + virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize, const SHA256_DIGEST *pWantedSha256, unsigned WantedCrc, unsigned WantedSize) = 0; + virtual bool RemoveFile(const char *pFilename, int Type) = 0; + virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0; + virtual bool CreateFolder(const char *pFoldername, int Type) = 0; + virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0; + virtual bool GetHashAndSize(const char *pFilename, int StorageType, SHA256_DIGEST *pSha256, unsigned *pCrc, unsigned *pSize) = 0; + virtual bool GetFileTime(const char *pFilename, int StorageType, time_t *pCreated, time_t *pModified) = 0; +}; + +IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments); +IStorage *CreateTestStorage(); + + +#endif diff --git a/src/game/collision.cpp b/src/game/collision.cpp new file mode 100644 index 000000000..5a0a361fc --- /dev/null +++ b/src/game/collision.cpp @@ -0,0 +1,208 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +CCollision::CCollision() +{ + m_pTiles = 0; + m_Width = 0; + m_Height = 0; + m_pLayers = 0; +} + +void CCollision::Init(class CLayers *pLayers) +{ + m_pLayers = pLayers; + m_Width = m_pLayers->GameLayer()->m_Width; + m_Height = m_pLayers->GameLayer()->m_Height; + m_pTiles = static_cast(m_pLayers->Map()->GetData(m_pLayers->GameLayer()->m_Data)); + + for(int i = 0; i < m_Width*m_Height; i++) + { + int Index = m_pTiles[i].m_Index; + + if(Index > 128) + continue; + + switch(Index) + { + case TILE_DEATH: + m_pTiles[i].m_Index = COLFLAG_DEATH; + break; + case TILE_SOLID: + m_pTiles[i].m_Index = COLFLAG_SOLID; + break; + case TILE_NOHOOK: + m_pTiles[i].m_Index = COLFLAG_SOLID|COLFLAG_NOHOOK; + break; + default: + m_pTiles[i].m_Index = 0; + } + } +} + +int CCollision::GetTile(int x, int y) const +{ + int Nx = clamp(x/32, 0, m_Width-1); + int Ny = clamp(y/32, 0, m_Height-1); + + return m_pTiles[Ny*m_Width+Nx].m_Index > 128 ? 0 : m_pTiles[Ny*m_Width+Nx].m_Index; +} + +bool CCollision::IsTile(int x, int y, int Flag) const +{ + return GetTile(x, y)&Flag; +} + +// TODO: rewrite this smarter! +int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) const +{ + const int End = distance(Pos0, Pos1)+1; + const float InverseEnd = 1.0f/End; + vec2 Last = Pos0; + + for(int i = 0; i <= End; i++) + { + vec2 Pos = mix(Pos0, Pos1, i*InverseEnd); + if(CheckPoint(Pos.x, Pos.y)) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return GetCollisionAt(Pos.x, Pos.y); + } + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +// TODO: OPT: rewrite this smarter! +void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces) const +{ + if(pBounces) + *pBounces = 0; + + vec2 Pos = *pInoutPos; + vec2 Vel = *pInoutVel; + if(CheckPoint(Pos + Vel)) + { + int Affected = 0; + if(CheckPoint(Pos.x + Vel.x, Pos.y)) + { + pInoutVel->x *= -Elasticity; + if(pBounces) + (*pBounces)++; + Affected++; + } + + if(CheckPoint(Pos.x, Pos.y + Vel.y)) + { + pInoutVel->y *= -Elasticity; + if(pBounces) + (*pBounces)++; + Affected++; + } + + if(Affected == 0) + { + pInoutVel->x *= -Elasticity; + pInoutVel->y *= -Elasticity; + } + } + else + { + *pInoutPos = Pos + Vel; + } +} + +bool CCollision::TestBox(vec2 Pos, vec2 Size, int Flag) const +{ + Size *= 0.5f; + if(CheckPoint(Pos.x-Size.x, Pos.y-Size.y, Flag)) + return true; + if(CheckPoint(Pos.x+Size.x, Pos.y-Size.y, Flag)) + return true; + if(CheckPoint(Pos.x-Size.x, Pos.y+Size.y, Flag)) + return true; + if(CheckPoint(Pos.x+Size.x, Pos.y+Size.y, Flag)) + return true; + return false; +} + +void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity, bool *pDeath) const +{ + // do the move + vec2 Pos = *pInoutPos; + vec2 Vel = *pInoutVel; + + const float Distance = length(Vel); + const int Max = (int)Distance; + + if(pDeath) + *pDeath = false; + + if(Distance > 0.00001f) + { + const float Fraction = 1.0f/(Max+1); + for(int i = 0; i <= Max; i++) + { + vec2 NewPos = Pos + Vel*Fraction; // TODO: this row is not nice + + //You hit a deathtile, congrats to that :) + //Deathtiles are a bit smaller + if(pDeath && TestBox(vec2(NewPos.x, NewPos.y), Size*(2.0f/3.0f), COLFLAG_DEATH)) + { + *pDeath = true; + } + + if(TestBox(vec2(NewPos.x, NewPos.y), Size)) + { + int Hits = 0; + + if(TestBox(vec2(Pos.x, NewPos.y), Size)) + { + NewPos.y = Pos.y; + Vel.y *= -Elasticity; + Hits++; + } + + if(TestBox(vec2(NewPos.x, Pos.y), Size)) + { + NewPos.x = Pos.x; + Vel.x *= -Elasticity; + Hits++; + } + + // neither of the tests got a collision. + // this is a real _corner case_! + if(Hits == 0) + { + NewPos.y = Pos.y; + Vel.y *= -Elasticity; + NewPos.x = Pos.x; + Vel.x *= -Elasticity; + } + } + + Pos = NewPos; + } + } + + *pInoutPos = Pos; + *pInoutVel = Vel; +} diff --git a/src/game/collision.h b/src/game/collision.h new file mode 100644 index 000000000..d04833de7 --- /dev/null +++ b/src/game/collision.h @@ -0,0 +1,39 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_COLLISION_H +#define GAME_COLLISION_H + +#include + +class CCollision +{ + struct CTile *m_pTiles; + int m_Width; + int m_Height; + class CLayers *m_pLayers; + + bool IsTile(int x, int y, int Flag=COLFLAG_SOLID) const; + int GetTile(int x, int y) const; + +public: + enum + { + COLFLAG_SOLID=1, + COLFLAG_DEATH=2, + COLFLAG_NOHOOK=4, + }; + + CCollision(); + void Init(class CLayers *pLayers); + bool CheckPoint(float x, float y, int Flag=COLFLAG_SOLID) const { return IsTile(round_to_int(x), round_to_int(y), Flag); } + bool CheckPoint(vec2 Pos, int Flag=COLFLAG_SOLID) const { return CheckPoint(Pos.x, Pos.y, Flag); } + int GetCollisionAt(float x, float y) const { return GetTile(round_to_int(x), round_to_int(y)); } + int GetWidth() const { return m_Width; } + int GetHeight() const { return m_Height; } + int IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) const; + void MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces) const; + void MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity, bool *pDeath=0) const; + bool TestBox(vec2 Pos, vec2 Size, int Flag=COLFLAG_SOLID) const; +}; + +#endif diff --git a/src/game/commands.h b/src/game/commands.h new file mode 100644 index 000000000..03a0dfba7 --- /dev/null +++ b/src/game/commands.h @@ -0,0 +1,174 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_COMMANDS_H +#define GAME_COMMANDS_H + +#include +#include +#include + +class CCommandManager +{ +public: + class CCommand + { + public: + char m_aName[16]; + char m_aHelpText[64]; + char m_aArgsFormat[64]; + + IConsole::FCommandCallback m_pfnCallback; + void *m_pContext; + + CCommand() + { + m_aName[0] = '\0'; + m_aHelpText[0] = '\0'; + m_aArgsFormat[0] = '\0'; + + m_pfnCallback = 0; + m_pContext = 0; + } + + CCommand(const char *pName, const char *pHelpText, const char *pArgsFormat, IConsole::FCommandCallback pfnCallback, void *pContext) + { + str_copy(m_aName, pName, sizeof(m_aName)); + str_copy(m_aHelpText, pHelpText, sizeof(m_aHelpText)); + str_copy(m_aArgsFormat, pArgsFormat, sizeof(m_aArgsFormat)); + m_pfnCallback = pfnCallback; + m_pContext = pContext; + } + }; + + typedef void (*FNewCommandHook)(const CCommand *pCommand, void *pContext); + typedef void (*FRemoveCommandHook)(const CCommand *pCommand, void *pContext); + +private: + array m_aCommands; + + IConsole *m_pConsole; + void *m_pHookContext; + FNewCommandHook m_pfnNewCommandHook; + FRemoveCommandHook m_pfnRemoveCommandHook; + +public: + CCommandManager() + { + m_pConsole = 0; + m_aCommands.clear(); + } + + void Init(IConsole *pConsole, void *pHookContext = 0, FNewCommandHook pfnNewCommandHook = 0, FRemoveCommandHook pfnRemoveCommandHook = 0) + { + m_pConsole = pConsole; + m_pHookContext = pHookContext; + m_pfnNewCommandHook = pfnNewCommandHook; + m_pfnRemoveCommandHook = pfnRemoveCommandHook; + } + + const CCommand *GetCommand(const char *pCommand) + { + for(int i = 0; i < m_aCommands.size(); i++) + if(!str_comp(m_aCommands[i].m_aName, pCommand)) + return &m_aCommands[i]; + + return 0; + } + + const CCommand *GetCommand(int Index) + { + if(Index < 0 || Index >= m_aCommands.size()) + return 0; + + return &m_aCommands[Index]; + } + + int AddCommand(const char *pCommand, const char *pHelpText, const char *pArgsFormat, IConsole::FCommandCallback pfnCallback, void *pContext) + { + const CCommand *pCom = GetCommand(pCommand); + if(pCom) + return 1; + + if(!m_pConsole->ArgStringIsValid(pArgsFormat)) + return 1; + + int Index = m_aCommands.add(CCommand(pCommand, pHelpText, pArgsFormat, pfnCallback, pContext)); + if(m_pfnNewCommandHook) + m_pfnNewCommandHook(&m_aCommands[Index], m_pHookContext); + + return 0; + } + + int RemoveCommand(const char *pCommand) + { + for(int i = 0; i < m_aCommands.size(); i++) + { + if(!str_comp(m_aCommands[i].m_aName, pCommand)) + { + if(m_pfnRemoveCommandHook) + m_pfnRemoveCommandHook(&m_aCommands[i], m_pHookContext); + + m_aCommands.remove_index(i); + return 0; + } + } + + return 1; + } + + void ClearCommands() + { + m_aCommands.clear(); + } + + int CommandCount() const + { + return m_aCommands.size(); + } + + struct SCommandContext + { + const char *m_pCommand; + const char *m_pArgs; + int m_ClientID; + void *m_pContext; + }; + + int OnCommand(const char *pCommand, const char *pArgs, int ClientID) + { + dbg_msg("chat_command", "calling '%s' with args '%s'", pCommand, pArgs); + const CCommand *pCom = GetCommand(pCommand); + if(!pCom) + return 1; + + SCommandContext Context = {pCom->m_aName, pArgs, ClientID, pCom->m_pContext}; + return m_pConsole->ParseCommandArgs(pArgs, pCom->m_aArgsFormat, pCom->m_pfnCallback, &Context); + } + + int Filter(array &aFilter, const char *pStr, bool Exact) + { + dbg_assert(aFilter.size() == m_aCommands.size(), "filter size must match command count"); + if(!*pStr) + { + for(int i = 0; i < aFilter.size(); i++) + aFilter[i] = false; + return 0; + } + + int Filtered = 0; + if(Exact) + { + for(int i = 0; i < m_aCommands.size(); i++) + Filtered += (aFilter[i] = str_comp(m_aCommands[i].m_aName, pStr)); + } + else + { + for(int i = 0; i < m_aCommands.size(); i++) + Filtered += (aFilter[i] = str_find_nocase(m_aCommands[i].m_aName, pStr) != m_aCommands[i].m_aName); + } + + return Filtered; + } +}; + +#endif //GAME_COMMANDS_H diff --git a/src/game/gamecore.cpp b/src/game/gamecore.cpp new file mode 100644 index 000000000..af7d3af46 --- /dev/null +++ b/src/game/gamecore.cpp @@ -0,0 +1,456 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "gamecore.h" + +const char *CTuningParams::s_apNames[] = +{ + #define MACRO_TUNING_PARAM(Name,ScriptName,Value) #ScriptName, + #include "tuning.h" + #undef MACRO_TUNING_PARAM +}; + + +bool CTuningParams::Set(int Index, float Value) +{ + if(Index < 0 || Index >= Num()) + return false; + ((CTuneParam *)this)[Index] = Value; + return true; +} + +bool CTuningParams::Get(int Index, float *pValue) const +{ + if(Index < 0 || Index >= Num()) + return false; + *pValue = (float)((CTuneParam *)this)[Index]; + return true; +} + +bool CTuningParams::Set(const char *pName, float Value) +{ + for(int i = 0; i < Num(); i++) + if(str_comp_nocase(pName, GetName(i)) == 0) + return Set(i, Value); + return false; +} + +bool CTuningParams::Get(const char *pName, float *pValue) const +{ + for(int i = 0; i < Num(); i++) + if(str_comp_nocase(pName, GetName(i)) == 0) + return Get(i, pValue); + return false; +} + +int CTuningParams::PossibleTunings(const char *pStr, IConsole::FPossibleCallback pfnCallback, void *pUser) +{ + int Index = 0; + for(int i = 0; i < Num(); i++) + { + if(str_find_nocase(GetName(i), pStr)) + { + pfnCallback(Index, GetName(i), pUser); + Index++; + } + } + return Index; +} + + +float VelocityRamp(float Value, float Start, float Range, float Curvature) +{ + if(Value < Start) + return 1.0f; + return 1.0f/powf(Curvature, (Value-Start)/Range); +} + +const float CCharacterCore::PHYS_SIZE = 28.0f; + +void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision) +{ + m_pWorld = pWorld; + m_pCollision = pCollision; +} + +void CCharacterCore::Reset() +{ + m_Pos = vec2(0,0); + m_Vel = vec2(0,0); + m_HookDragVel = vec2(0,0); + m_HookPos = vec2(0,0); + m_HookDir = vec2(0,0); + m_HookTick = 0; + m_HookState = HOOK_IDLE; + m_HookedPlayer = -1; + m_Jumped = 0; + m_TriggeredEvents = 0; + m_Death = false; +} + +void CCharacterCore::Tick(bool UseInput) +{ + m_TriggeredEvents = 0; + + // get ground state + const bool Grounded = + m_pCollision->CheckPoint(m_Pos.x+PHYS_SIZE/2, m_Pos.y+PHYS_SIZE/2+5) + || m_pCollision->CheckPoint(m_Pos.x-PHYS_SIZE/2, m_Pos.y+PHYS_SIZE/2+5); + + vec2 TargetDirection = normalize(vec2(m_Input.m_TargetX, m_Input.m_TargetY)); + + m_Vel.y += m_pWorld->m_Tuning.m_Gravity; + + float MaxSpeed = Grounded ? m_pWorld->m_Tuning.m_GroundControlSpeed : m_pWorld->m_Tuning.m_AirControlSpeed; + float Accel = Grounded ? m_pWorld->m_Tuning.m_GroundControlAccel : m_pWorld->m_Tuning.m_AirControlAccel; + float Friction = Grounded ? m_pWorld->m_Tuning.m_GroundFriction : m_pWorld->m_Tuning.m_AirFriction; + + // handle input + if(UseInput) + { + m_Direction = m_Input.m_Direction; + m_Angle = (int)(angle(vec2(m_Input.m_TargetX, m_Input.m_TargetY))*256.0f); + + // handle jump + if(m_Input.m_Jump) + { + if(!(m_Jumped&1)) + { + if(Grounded) + { + m_TriggeredEvents |= COREEVENTFLAG_GROUND_JUMP; + m_Vel.y = -m_pWorld->m_Tuning.m_GroundJumpImpulse; + m_Jumped |= 1; + } + else if(!(m_Jumped&2)) + { + m_TriggeredEvents |= COREEVENTFLAG_AIR_JUMP; + m_Vel.y = -m_pWorld->m_Tuning.m_AirJumpImpulse; + m_Jumped |= 3; + } + } + } + else + m_Jumped &= ~1; + + // handle hook + if(m_Input.m_Hook) + { + if(m_HookState == HOOK_IDLE) + { + m_HookState = HOOK_FLYING; + m_HookPos = m_Pos+TargetDirection*PHYS_SIZE*1.5f; + m_HookDir = TargetDirection; + m_HookedPlayer = -1; + m_HookTick = 0; + //m_TriggeredEvents |= COREEVENTFLAG_HOOK_LAUNCH; + } + } + else + { + m_HookedPlayer = -1; + m_HookState = HOOK_IDLE; + m_HookPos = m_Pos; + } + } + + // add the speed modification according to players wanted direction + if(m_Direction < 0) + m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, -Accel); + if(m_Direction > 0) + m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, Accel); + if(m_Direction == 0) + m_Vel.x *= Friction; + + // handle jumping + // 1 bit = to keep track if a jump has been made on this input + // 2 bit = to keep track if a air-jump has been made + if(Grounded) + m_Jumped &= ~2; + + // do hook + if(m_HookState == HOOK_IDLE) + { + m_HookedPlayer = -1; + m_HookState = HOOK_IDLE; + m_HookPos = m_Pos; + } + else if(m_HookState >= HOOK_RETRACT_START && m_HookState < HOOK_RETRACT_END) + { + m_HookState++; + } + else if(m_HookState == HOOK_RETRACT_END) + { + m_HookState = HOOK_RETRACTED; + //m_TriggeredEvents |= COREEVENTFLAG_HOOK_RETRACT; + } + else if(m_HookState == HOOK_FLYING) + { + vec2 NewPos = m_HookPos+m_HookDir*m_pWorld->m_Tuning.m_HookFireSpeed; + if(distance(m_Pos, NewPos) > m_pWorld->m_Tuning.m_HookLength) + { + m_HookState = HOOK_RETRACT_START; + NewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning.m_HookLength; + } + + // make sure that the hook doesn't go though the ground + bool GoingToHitGround = false; + bool GoingToRetract = false; + int Hit = m_pCollision->IntersectLine(m_HookPos, NewPos, &NewPos, 0); + if(Hit) + { + if(Hit&CCollision::COLFLAG_NOHOOK) + GoingToRetract = true; + else + GoingToHitGround = true; + } + + // Check against other players first + if(m_pWorld && m_pWorld->m_Tuning.m_PlayerHooking) + { + float Distance = 0.0f; + for(int i = 0; i < MAX_CLIENTS; i++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; + if(!pCharCore || pCharCore == this) + continue; + + vec2 ClosestPoint = closest_point_on_line(m_HookPos, NewPos, pCharCore->m_Pos); + if(distance(pCharCore->m_Pos, ClosestPoint) < PHYS_SIZE+2.0f) + { + if(m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance) + { + m_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_PLAYER; + m_HookState = HOOK_GRABBED; + m_HookedPlayer = i; + Distance = distance(m_HookPos, pCharCore->m_Pos); + } + } + } + } + + if(m_HookState == HOOK_FLYING) + { + // check against ground + if(GoingToHitGround) + { + m_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_GROUND; + m_HookState = HOOK_GRABBED; + } + else if(GoingToRetract) + { + m_TriggeredEvents |= COREEVENTFLAG_HOOK_HIT_NOHOOK; + m_HookState = HOOK_RETRACT_START; + } + + m_HookPos = NewPos; + } + } + + if(m_HookState == HOOK_GRABBED) + { + if(m_HookedPlayer != -1) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[m_HookedPlayer]; + if(pCharCore) + m_HookPos = pCharCore->m_Pos; + else + { + // release hook + m_HookedPlayer = -1; + m_HookState = HOOK_RETRACTED; + m_HookPos = m_Pos; + } + + // keep players hooked for a max of 1.5sec + //if(Server()->Tick() > hook_tick+(Server()->TickSpeed()*3)/2) + //release_hooked(); + } + + // don't do this hook rutine when we are hook to a player + if(m_HookedPlayer == -1 && distance(m_HookPos, m_Pos) > 46.0f) + { + vec2 HookVel = normalize(m_HookPos-m_Pos)*m_pWorld->m_Tuning.m_HookDragAccel; + // the hook as more power to drag you up then down. + // this makes it easier to get on top of an platform + if(HookVel.y > 0) + HookVel.y *= 0.3f; + + // the hook will boost it's power if the player wants to move + // in that direction. otherwise it will dampen everything abit + if((HookVel.x < 0 && m_Direction < 0) || (HookVel.x > 0 && m_Direction > 0)) + HookVel.x *= 0.95f; + else + HookVel.x *= 0.75f; + + vec2 NewVel = m_Vel+HookVel; + + // check if we are under the legal limit for the hook + if(length(NewVel) < m_pWorld->m_Tuning.m_HookDragSpeed || length(NewVel) < length(m_Vel)) + m_Vel = NewVel; // no problem. apply + + } + + // release hook (max hook time is 1.25 + m_HookTick++; + if(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED+SERVER_TICK_SPEED/5 || !m_pWorld->m_apCharacters[m_HookedPlayer])) + { + m_HookedPlayer = -1; + m_HookState = HOOK_RETRACTED; + m_HookPos = m_Pos; + } + } + + if(m_pWorld) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; + if(!pCharCore) + continue; + + //player *p = (player*)ent; + if(pCharCore == this) // || !(p->flags&FLAG_ALIVE) + continue; // make sure that we don't nudge our self + + // handle player <-> player collision + float Distance = distance(m_Pos, pCharCore->m_Pos); + vec2 Dir = normalize(m_Pos - pCharCore->m_Pos); + if(m_pWorld->m_Tuning.m_PlayerCollision && Distance < PHYS_SIZE*1.25f && Distance > 0.0f) + { + float a = (PHYS_SIZE*1.45f - Distance); + float Velocity = 0.5f; + + // make sure that we don't add excess force by checking the + // direction against the current velocity. if not zero. + if(length(m_Vel) > 0.0001) + Velocity = 1-(dot(normalize(m_Vel), Dir)+1)/2; + + m_Vel += Dir*a*(Velocity*0.75f); + m_Vel *= 0.85f; + } + + // handle hook influence + if(m_HookedPlayer == i && m_pWorld->m_Tuning.m_PlayerHooking) + { + if(Distance > PHYS_SIZE*1.50f) // TODO: fix tweakable variable + { + float Accel = m_pWorld->m_Tuning.m_HookDragAccel * (Distance/m_pWorld->m_Tuning.m_HookLength); + + // add force to the hooked player + pCharCore->m_HookDragVel += Dir*Accel*1.5f; + + // add a little bit force to the guy who has the grip + m_HookDragVel -= Dir*Accel*0.25f; + } + } + } + } + + // clamp the velocity to something sane + if(length(m_Vel) > 6000) + m_Vel = normalize(m_Vel) * 6000; +} + +void CCharacterCore::AddDragVelocity() +{ + // Apply hook interaction velocity + float DragSpeed = m_pWorld->m_Tuning.m_HookDragSpeed; + + m_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, m_HookDragVel.x); + m_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, m_HookDragVel.y); +} + +void CCharacterCore::ResetDragVelocity() +{ + m_HookDragVel = vec2(0,0); +} + +void CCharacterCore::Move() +{ + if(!m_pWorld) + return; + + float RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning.m_VelrampStart, m_pWorld->m_Tuning.m_VelrampRange, m_pWorld->m_Tuning.m_VelrampCurvature); + + m_Vel.x = m_Vel.x*RampValue; + + vec2 NewPos = m_Pos; + m_pCollision->MoveBox(&NewPos, &m_Vel, vec2(PHYS_SIZE, PHYS_SIZE), 0, &m_Death); + + m_Vel.x = m_Vel.x*(1.0f/RampValue); + + if(m_pWorld->m_Tuning.m_PlayerCollision) + { + // check player collision + float Distance = distance(m_Pos, NewPos); + int End = Distance+1; + vec2 LastPos = m_Pos; + for(int i = 0; i < End; i++) + { + float a = i/Distance; + vec2 Pos = mix(m_Pos, NewPos, a); + for(int p = 0; p < MAX_CLIENTS; p++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[p]; + if(!pCharCore || pCharCore == this) + continue; + float D = distance(Pos, pCharCore->m_Pos); + if(D < PHYS_SIZE && D >= 0.0f) + { + if(a > 0.0f) + m_Pos = LastPos; + else if(distance(NewPos, pCharCore->m_Pos) > D) + m_Pos = NewPos; + return; + } + } + LastPos = Pos; + } + } + + m_Pos = NewPos; +} + +void CCharacterCore::Write(CNetObj_CharacterCore *pObjCore) const +{ + pObjCore->m_X = round_to_int(m_Pos.x); + pObjCore->m_Y = round_to_int(m_Pos.y); + + pObjCore->m_VelX = round_to_int(m_Vel.x*256.0f); + pObjCore->m_VelY = round_to_int(m_Vel.y*256.0f); + pObjCore->m_HookState = m_HookState; + pObjCore->m_HookTick = m_HookTick; + pObjCore->m_HookX = round_to_int(m_HookPos.x); + pObjCore->m_HookY = round_to_int(m_HookPos.y); + pObjCore->m_HookDx = round_to_int(m_HookDir.x*256.0f); + pObjCore->m_HookDy = round_to_int(m_HookDir.y*256.0f); + pObjCore->m_HookedPlayer = m_HookedPlayer; + pObjCore->m_Jumped = m_Jumped; + pObjCore->m_Direction = m_Direction; + pObjCore->m_Angle = m_Angle; +} + +void CCharacterCore::Read(const CNetObj_CharacterCore *pObjCore) +{ + m_Pos.x = pObjCore->m_X; + m_Pos.y = pObjCore->m_Y; + m_Vel.x = pObjCore->m_VelX/256.0f; + m_Vel.y = pObjCore->m_VelY/256.0f; + m_HookState = pObjCore->m_HookState; + m_HookTick = pObjCore->m_HookTick; + m_HookPos.x = pObjCore->m_HookX; + m_HookPos.y = pObjCore->m_HookY; + m_HookDir.x = pObjCore->m_HookDx/256.0f; + m_HookDir.y = pObjCore->m_HookDy/256.0f; + m_HookedPlayer = pObjCore->m_HookedPlayer; + m_Jumped = pObjCore->m_Jumped; + m_Direction = pObjCore->m_Direction; + m_Angle = pObjCore->m_Angle; +} + +void CCharacterCore::Quantize() +{ + CNetObj_CharacterCore Core; + Write(&Core); + Read(&Core); +} diff --git a/src/game/gamecore.h b/src/game/gamecore.h new file mode 100644 index 000000000..f442ee337 --- /dev/null +++ b/src/game/gamecore.h @@ -0,0 +1,187 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_GAMECORE_H +#define GAME_GAMECORE_H + +#include +#include + +#include +#include "collision.h" +#include +#include +#include + +class CTuneParam +{ + int m_Value; +public: + void Set(int v) { m_Value = v; } + int Get() const { return m_Value; } + CTuneParam &operator = (int v) { m_Value = (int)(v*100.0f); return *this; } + CTuneParam &operator = (float v) { m_Value = (int)(v*100.0f); return *this; } + operator float() const { return m_Value/100.0f; } +}; + +class CTuningParams +{ + static const char *s_apNames[]; +public: + CTuningParams() + { + const float TicksPerSecond = 50.0f; + #define MACRO_TUNING_PARAM(Name,ScriptName,Value) m_##Name.Set((int)(Value*100.0f)); + #include "tuning.h" + #undef MACRO_TUNING_PARAM + } + + #define MACRO_TUNING_PARAM(Name,ScriptName,Value) CTuneParam m_##Name; + #include "tuning.h" + #undef MACRO_TUNING_PARAM + + static int Num() { return sizeof(CTuningParams)/sizeof(int); } + bool Set(int Index, float Value); + bool Set(const char *pName, float Value); + bool Get(int Index, float *pValue) const; + bool Get(const char *pName, float *pValue) const; + const char *GetName(int Index) const { return s_apNames[Index]; } + int PossibleTunings(const char *pStr, IConsole::FPossibleCallback pfnCallback = IConsole::EmptyPossibleCommandCallback, void *pUser = 0); +}; + +inline void StrToInts(int *pInts, int Num, const char *pStr) +{ + int Index = 0; + while(Num) + { + char aBuf[4] = {0,0,0,0}; + for(int c = 0; c < 4 && pStr[Index]; c++, Index++) + aBuf[c] = pStr[Index]; + *pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128); + pInts++; + Num--; + } + + // null terminate + pInts[-1] &= 0xffffff00; +} + +inline void IntsToStr(const int *pInts, int Num, char *pStr) +{ + while(Num) + { + pStr[0] = (((*pInts)>>24)&0xff)-128; + pStr[1] = (((*pInts)>>16)&0xff)-128; + pStr[2] = (((*pInts)>>8)&0xff)-128; + pStr[3] = ((*pInts)&0xff)-128; + pStr += 4; + pInts++; + Num--; + } + + // null terminate + pStr[-1] = 0; +} + + + +inline vec2 CalcPos(vec2 Pos, vec2 Velocity, float Curvature, float Speed, float Time) +{ + vec2 n; + Time *= Speed; + n.x = Pos.x + Velocity.x*Time; + n.y = Pos.y + Velocity.y*Time + Curvature/10000*(Time*Time); + return n; +} + + +template +inline T SaturatedAdd(T Min, T Max, T Current, T Modifier) +{ + if(Modifier < 0) + { + if(Current < Min) + return Current; + Current += Modifier; + if(Current < Min) + Current = Min; + return Current; + } + else + { + if(Current > Max) + return Current; + Current += Modifier; + if(Current > Max) + Current = Max; + return Current; + } +} + + +float VelocityRamp(float Value, float Start, float Range, float Curvature); + +// hooking stuff +enum +{ + HOOK_RETRACTED=-1, + HOOK_IDLE=0, + HOOK_RETRACT_START=1, + HOOK_RETRACT_END=3, + HOOK_FLYING, + HOOK_GRABBED, +}; + +class CWorldCore +{ +public: + CWorldCore() + { + mem_zero(m_apCharacters, sizeof(m_apCharacters)); + } + + CTuningParams m_Tuning; + class CCharacterCore *m_apCharacters[MAX_CLIENTS]; +}; + +class CCharacterCore +{ + CWorldCore *m_pWorld; + CCollision *m_pCollision; +public: + static const float PHYS_SIZE; + vec2 m_Pos; + vec2 m_Vel; + + vec2 m_HookDragVel; + + vec2 m_HookPos; + vec2 m_HookDir; + int m_HookTick; + int m_HookState; + int m_HookedPlayer; + + int m_Jumped; + + int m_Direction; + int m_Angle; + + bool m_Death; + + CNetObj_PlayerInput m_Input; + + int m_TriggeredEvents; + + void Init(CWorldCore *pWorld, CCollision *pCollision); + void Reset(); + void Tick(bool UseInput); + void Move(); + + void AddDragVelocity(); + void ResetDragVelocity(); + + void Read(const CNetObj_CharacterCore *pObjCore); + void Write(CNetObj_CharacterCore *pObjCore) const; + void Quantize(); +}; + +#endif diff --git a/src/game/layers.cpp b/src/game/layers.cpp new file mode 100644 index 000000000..ac62efdb5 --- /dev/null +++ b/src/game/layers.cpp @@ -0,0 +1,104 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "layers.h" + +CLayers::CLayers() +{ + m_GroupsNum = 0; + m_GroupsStart = 0; + m_LayersNum = 0; + m_LayersStart = 0; + m_pGameGroup = 0; + m_pGameLayer = 0; + m_pMap = 0; +} + +void CLayers::Init(class IKernel *pKernel, IMap *pMap) +{ + m_pMap = pMap ? pMap : pKernel->RequestInterface(); + m_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum); + m_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum); + + InitGameLayer(); + InitTilemapSkip(); +} + +void CLayers::InitGameLayer() +{ + for(int g = 0; g < NumGroups(); g++) + { + CMapItemGroup *pGroup = GetGroup(g); + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); + if(pLayer->m_Type == LAYERTYPE_TILES) + { + CMapItemLayerTilemap *pTilemap = reinterpret_cast(pLayer); + if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) + { + m_pGameLayer = pTilemap; + m_pGameGroup = pGroup; + + // make sure the game group has standard settings + m_pGameGroup->m_OffsetX = 0; + m_pGameGroup->m_OffsetY = 0; + m_pGameGroup->m_ParallaxX = 100; + m_pGameGroup->m_ParallaxY = 100; + + if(m_pGameGroup->m_Version >= 2) + { + m_pGameGroup->m_UseClipping = 0; + m_pGameGroup->m_ClipX = 0; + m_pGameGroup->m_ClipY = 0; + m_pGameGroup->m_ClipW = 0; + m_pGameGroup->m_ClipH = 0; + } + + return; // there can only be one game layer and game group + } + } + } + } +} + +void CLayers::InitTilemapSkip() +{ + for(int g = 0; g < NumGroups(); g++) + { + CMapItemGroup *pGroup = GetGroup(g); + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); + if(pLayer->m_Type == LAYERTYPE_TILES) + { + CMapItemLayerTilemap *pTilemap = (CMapItemLayerTilemap *)pLayer; + CTile *pTiles = (CTile *)Map()->GetData(pTilemap->m_Data); + for(int y = 0; y < pTilemap->m_Height; y++) + { + for(int x = 1; x < pTilemap->m_Width;) + { + int SkippedX; + for(SkippedX = 1; x+SkippedX < pTilemap->m_Width && SkippedX < 255; SkippedX++) + { + if(pTiles[y*pTilemap->m_Width+x+SkippedX].m_Index) + break; + } + + pTiles[y*pTilemap->m_Width+x].m_Skip = SkippedX-1; + x += SkippedX; + } + } + } + } + } +} + +CMapItemGroup *CLayers::GetGroup(int Index) const +{ + return static_cast(m_pMap->GetItem(m_GroupsStart+Index, 0, 0)); +} + +CMapItemLayer *CLayers::GetLayer(int Index) const +{ + return static_cast(m_pMap->GetItem(m_LayersStart+Index, 0, 0)); +} diff --git a/src/game/layers.h b/src/game/layers.h new file mode 100644 index 000000000..8efd7751e --- /dev/null +++ b/src/game/layers.h @@ -0,0 +1,34 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_LAYERS_H +#define GAME_LAYERS_H + +#include +#include + +class CLayers +{ + int m_GroupsNum; + int m_GroupsStart; + int m_LayersNum; + int m_LayersStart; + CMapItemGroup *m_pGameGroup; + CMapItemLayerTilemap *m_pGameLayer; + class IMap *m_pMap; + + void InitGameLayer(); + void InitTilemapSkip(); + +public: + CLayers(); + void Init(class IKernel *pKernel, class IMap *pMap=0); + int NumGroups() const { return m_GroupsNum; } + int NumLayers() const { return m_LayersNum; } + class IMap *Map() const { return m_pMap; } + CMapItemGroup *GameGroup() const { return m_pGameGroup; } + CMapItemLayerTilemap *GameLayer() const { return m_pGameLayer; } + CMapItemGroup *GetGroup(int Index) const; + CMapItemLayer *GetLayer(int Index) const; +}; + +#endif diff --git a/src/game/mapitems.h b/src/game/mapitems.h new file mode 100644 index 000000000..46157637a --- /dev/null +++ b/src/game/mapitems.h @@ -0,0 +1,236 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_MAPITEMS_H +#define GAME_MAPITEMS_H + +// layer types +enum +{ + LAYERTYPE_INVALID=0, + LAYERTYPE_GAME, + LAYERTYPE_TILES, + LAYERTYPE_QUADS, + + MAPITEMTYPE_VERSION=0, + MAPITEMTYPE_INFO, + MAPITEMTYPE_IMAGE, + MAPITEMTYPE_ENVELOPE, + MAPITEMTYPE_GROUP, + MAPITEMTYPE_LAYER, + MAPITEMTYPE_ENVPOINTS, + + + CURVETYPE_STEP=0, + CURVETYPE_LINEAR, + CURVETYPE_SLOW, + CURVETYPE_FAST, + CURVETYPE_SMOOTH, + CURVETYPE_BEZIER, + NUM_CURVETYPES, + + // game layer tiles + ENTITY_NULL=0, + ENTITY_SPAWN, + ENTITY_SPAWN_RED, + ENTITY_SPAWN_BLUE, + ENTITY_FLAGSTAND_RED, + ENTITY_FLAGSTAND_BLUE, + ENTITY_ARMOR_1, + ENTITY_HEALTH_1, + ENTITY_WEAPON_SHOTGUN, + ENTITY_WEAPON_GRENADE, + ENTITY_POWERUP_NINJA, + ENTITY_WEAPON_LASER, + NUM_ENTITIES, + + TILE_AIR=0, + TILE_SOLID, + TILE_DEATH, + TILE_NOHOOK, + + TILEFLAG_VFLIP=1, + TILEFLAG_HFLIP=2, + TILEFLAG_OPAQUE=4, + TILEFLAG_ROTATE=8, + + LAYERFLAG_DETAIL=1, + TILESLAYERFLAG_GAME=1, + + ENTITY_OFFSET=255-16*4, +}; + +struct CPoint +{ + int x, y; // 22.10 fixed point +}; + +struct CColor +{ + int r, g, b, a; +}; + +struct CQuad +{ + CPoint m_aPoints[5]; + CColor m_aColors[4]; + CPoint m_aTexcoords[4]; + + int m_PosEnv; + int m_PosEnvOffset; + + int m_ColorEnv; + int m_ColorEnvOffset; +}; + +struct CTile +{ + unsigned char m_Index; + unsigned char m_Flags; + unsigned char m_Skip; + unsigned char m_Reserved; +}; + +struct CMapItemInfo +{ + enum { CURRENT_VERSION=1 }; + int m_Version; + int m_Author; + int m_MapVersion; + int m_Credits; + int m_License; +} ; + +struct CMapItemImage_v1 +{ + int m_Version; + int m_Width; + int m_Height; + int m_External; + int m_ImageName; + int m_ImageData; +} ; + +struct CMapItemImage : public CMapItemImage_v1 +{ + enum { CURRENT_VERSION=2 }; + int m_Format; +}; + +struct CMapItemGroup_v1 +{ + int m_Version; + int m_OffsetX; + int m_OffsetY; + int m_ParallaxX; + int m_ParallaxY; + + int m_StartLayer; + int m_NumLayers; +} ; + + +struct CMapItemGroup : public CMapItemGroup_v1 +{ + enum { CURRENT_VERSION=3 }; + + int m_UseClipping; + int m_ClipX; + int m_ClipY; + int m_ClipW; + int m_ClipH; + + int m_aName[3]; +} ; + +struct CMapItemLayer +{ + int m_Version; + int m_Type; + int m_Flags; +} ; + +struct CMapItemLayerTilemap +{ + enum { CURRENT_VERSION=4 }; + + CMapItemLayer m_Layer; + int m_Version; + + int m_Width; + int m_Height; + int m_Flags; + + CColor m_Color; + int m_ColorEnv; + int m_ColorEnvOffset; + + int m_Image; + int m_Data; + + int m_aName[3]; +} ; + +struct CMapItemLayerQuads +{ + enum { CURRENT_VERSION=2 }; + + CMapItemLayer m_Layer; + int m_Version; + + int m_NumQuads; + int m_Data; + int m_Image; + + int m_aName[3]; +} ; + +struct CMapItemVersion +{ + enum { CURRENT_VERSION=1 }; + + int m_Version; +} ; + +struct CEnvPoint_v1 +{ + int m_Time; // in ms + int m_Curvetype; + int m_aValues[4]; // 1-4 depending on envelope (22.10 fixed point) + + bool operator<(const CEnvPoint_v1 &Other) const { return m_Time < Other.m_Time; } +} ; + +struct CEnvPoint : public CEnvPoint_v1 +{ + // bezier curve only + // dx in ms and dy as 22.10 fxp + int m_aInTangentdx[4]; + int m_aInTangentdy[4]; + int m_aOutTangentdx[4]; + int m_aOutTangentdy[4]; + + bool operator<(const CEnvPoint& other) const { return m_Time < other.m_Time; } +}; + +struct CMapItemEnvelope_v1 +{ + int m_Version; + int m_Channels; + int m_StartPoint; + int m_NumPoints; + int m_aName[8]; +} ; + +struct CMapItemEnvelope_v2 : public CMapItemEnvelope_v1 +{ + enum { CURRENT_VERSION=2 }; + int m_Synchronized; +}; + +struct CMapItemEnvelope : public CMapItemEnvelope_v2 +{ + // bezier curve support + enum { CURRENT_VERSION=3 }; +}; + +#endif diff --git a/src/game/server/alloc.h b/src/game/server/alloc.h new file mode 100644 index 000000000..5806d6067 --- /dev/null +++ b/src/game/server/alloc.h @@ -0,0 +1,62 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ALLOC_H +#define GAME_SERVER_ALLOC_H + +#include + +#include + +#define MACRO_ALLOC_HEAP() \ + public: \ + void *operator new(size_t Size) \ + { \ + void *p = mem_alloc(Size); \ + /*dbg_msg("", "++ %p %d", p, size);*/ \ + mem_zero(p, Size); \ + return p; \ + } \ + void operator delete(void *pPtr) \ + { \ + /*dbg_msg("", "-- %p", p);*/ \ + mem_free(pPtr); \ + } \ + private: + +#define MACRO_ALLOC_POOL_ID() \ + public: \ + void *operator new(size_t Size, int id); \ + void operator delete(void *p, int id); \ + void operator delete(void *p); \ + private: + +#define MACRO_ALLOC_POOL_ID_IMPL(POOLTYPE, PoolSize) \ + static char ms_PoolData##POOLTYPE[PoolSize][sizeof(POOLTYPE)] = {{0}}; \ + static int ms_PoolUsed##POOLTYPE[PoolSize] = {0}; \ + void *POOLTYPE::operator new(size_t Size, int id) \ + { \ + dbg_assert(sizeof(POOLTYPE) == Size, "size error"); \ + dbg_assert(!ms_PoolUsed##POOLTYPE[id], "already used"); \ + /*dbg_msg("pool", "++ %s %d", #POOLTYPE, id);*/ \ + ms_PoolUsed##POOLTYPE[id] = 1; \ + mem_zero(ms_PoolData##POOLTYPE[id], Size); \ + return ms_PoolData##POOLTYPE[id]; \ + } \ + void POOLTYPE::operator delete(void *p, int id) \ + { \ + dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ + dbg_assert(id == (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE, "invalid id"); \ + /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ + ms_PoolUsed##POOLTYPE[id] = 0; \ + mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ + } \ + void POOLTYPE::operator delete(void *p) \ + { \ + int id = (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE; \ + dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ + /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ + ms_PoolUsed##POOLTYPE[id] = 0; \ + mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ + } + +#endif diff --git a/src/game/server/entities/character.cpp b/src/game/server/entities/character.cpp new file mode 100644 index 000000000..25dac5a3e --- /dev/null +++ b/src/game/server/entities/character.cpp @@ -0,0 +1,868 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include + +#include "character.h" +#include "laser.h" +#include "projectile.h" + +//input count +struct CInputCount +{ + int m_Presses; + int m_Releases; +}; + +CInputCount CountInput(int Prev, int Cur) +{ + CInputCount c = {0, 0}; + Prev &= INPUT_STATE_MASK; + Cur &= INPUT_STATE_MASK; + int i = Prev; + + while(i != Cur) + { + i = (i+1)&INPUT_STATE_MASK; + if(i&1) + c.m_Presses++; + else + c.m_Releases++; + } + + return c; +} + + +MACRO_ALLOC_POOL_ID_IMPL(CCharacter, MAX_CLIENTS) + +// Character, "physical" player's part +CCharacter::CCharacter(CGameWorld *pWorld) +: CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER, vec2(0, 0), ms_PhysSize) +{ + m_Health = 0; + m_Armor = 0; + m_TriggeredEvents = 0; +} + +void CCharacter::Reset() +{ + Destroy(); +} + +bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) +{ + m_EmoteStop = -1; + m_LastAction = -1; + m_LastNoAmmoSound = -1; + m_ActiveWeapon = WEAPON_GUN; + m_LastWeapon = WEAPON_HAMMER; + m_QueuedWeapon = -1; + + m_pPlayer = pPlayer; + m_Pos = Pos; + + m_Core.Reset(); + m_Core.Init(&GameWorld()->m_Core, GameServer()->Collision()); + m_Core.m_Pos = m_Pos; + GameWorld()->m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; + + m_ReckoningTick = 0; + mem_zero(&m_SendCore, sizeof(m_SendCore)); + mem_zero(&m_ReckoningCore, sizeof(m_ReckoningCore)); + + GameWorld()->InsertEntity(this); + m_Alive = true; + + GameServer()->m_pController->OnCharacterSpawn(this); + + return true; +} + +void CCharacter::Destroy() +{ + GameWorld()->m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; + m_Alive = false; +} + +void CCharacter::SetWeapon(int W) +{ + if(W == m_ActiveWeapon) + return; + + m_LastWeapon = m_ActiveWeapon; + m_QueuedWeapon = -1; + m_ActiveWeapon = W; + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SWITCH); + + if(m_ActiveWeapon < 0 || m_ActiveWeapon >= NUM_WEAPONS) + m_ActiveWeapon = 0; + m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; +} + +bool CCharacter::IsGrounded() +{ + if(GameServer()->Collision()->CheckPoint(m_Pos.x+GetProximityRadius()/2, m_Pos.y+GetProximityRadius()/2+5)) + return true; + if(GameServer()->Collision()->CheckPoint(m_Pos.x-GetProximityRadius()/2, m_Pos.y+GetProximityRadius()/2+5)) + return true; + return false; +} + + +void CCharacter::HandleNinja() +{ + if(m_ActiveWeapon != WEAPON_NINJA) + return; + + if((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) + { + // time's up, return + m_aWeapons[WEAPON_NINJA].m_Got = false; + m_ActiveWeapon = m_LastWeapon; + + // reset velocity and current move + if(m_Ninja.m_CurrentMoveTime > 0) + m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; + m_Ninja.m_CurrentMoveTime = -1; + + SetWeapon(m_ActiveWeapon); + return; + } + + // force ninja Weapon + SetWeapon(WEAPON_NINJA); + + m_Ninja.m_CurrentMoveTime--; + + if(m_Ninja.m_CurrentMoveTime == 0) + { + // reset velocity + m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; + } + else if(m_Ninja.m_CurrentMoveTime > 0) + { + // Set velocity + m_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity; + vec2 OldPos = m_Pos; + GameServer()->Collision()->MoveBox(&m_Core.m_Pos, &m_Core.m_Vel, vec2(GetProximityRadius(), GetProximityRadius()), 0.f); + + // reset velocity so the client doesn't predict stuff + m_Core.m_Vel = vec2(0.f, 0.f); + + // check if we hit anything along the way + const float Radius = GetProximityRadius() * 2.0f; + const vec2 Center = OldPos + (m_Pos - OldPos) * 0.5f; + CCharacter *aEnts[MAX_CLIENTS]; + const int Num = GameWorld()->FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + for(int i = 0; i < Num; ++i) + { + if(aEnts[i] == this) + continue; + + // make sure we haven't hit this object before + bool AlreadyHit = false; + for(int j = 0; j < m_NumObjectsHit; j++) + { + if(m_apHitObjects[j] == aEnts[i]) + { + AlreadyHit = true; + break; + } + } + if(AlreadyHit) + continue; + + // check so we are sufficiently close + if(distance(aEnts[i]->m_Pos, m_Pos) > Radius) + continue; + + // Hit a player, give him damage and stuffs... + GameServer()->CreateSound(aEnts[i]->m_Pos, SOUND_NINJA_HIT); + if(m_NumObjectsHit < MAX_PLAYERS) + m_apHitObjects[m_NumObjectsHit++] = aEnts[i]; + + // set his velocity to fast upward (for now) + aEnts[i]->TakeDamage(vec2(0, -10.0f), m_Ninja.m_ActivationDir*-1, g_pData->m_Weapons.m_Ninja.m_pBase->m_Damage, m_pPlayer->GetCID(), WEAPON_NINJA); + } + } +} + + +void CCharacter::DoWeaponSwitch() +{ + // make sure we can switch + if(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got) + return; + + // switch Weapon + SetWeapon(m_QueuedWeapon); +} + +void CCharacter::HandleWeaponSwitch() +{ + int WantedWeapon = m_ActiveWeapon; + if(m_QueuedWeapon != -1) + WantedWeapon = m_QueuedWeapon; + + // select Weapon + int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses; + int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses; + + if(Next < 128) // make sure we only try sane stuff + { + while(Next) // Next Weapon selection + { + WantedWeapon = (WantedWeapon+1)%NUM_WEAPONS; + if(m_aWeapons[WantedWeapon].m_Got) + Next--; + } + } + + if(Prev < 128) // make sure we only try sane stuff + { + while(Prev) // Prev Weapon selection + { + WantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1; + if(m_aWeapons[WantedWeapon].m_Got) + Prev--; + } + } + + // Direct Weapon selection + if(m_LatestInput.m_WantedWeapon) + WantedWeapon = m_Input.m_WantedWeapon-1; + + // check for insane values + if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) + m_QueuedWeapon = WantedWeapon; + + DoWeaponSwitch(); +} + +void CCharacter::FireWeapon() +{ + if(m_ReloadTimer != 0) + return; + + DoWeaponSwitch(); + vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); + + bool FullAuto = false; + if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_LASER) + FullAuto = true; + + + // check if we gonna fire + bool WillFire = false; + if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) + WillFire = true; + + if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo) + WillFire = true; + + if(!WillFire) + return; + + // check for ammo + if(!m_aWeapons[m_ActiveWeapon].m_Ammo) + { + // 125ms is a magical limit of how fast a human can click + m_ReloadTimer = 125 * Server()->TickSpeed() / 1000; + if(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick()) + { + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO); + m_LastNoAmmoSound = Server()->Tick(); + } + return; + } + + vec2 ProjStartPos = m_Pos+Direction*GetProximityRadius()*0.75f; + + if(Config()->m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "shot player='%d:%s' team=%d weapon=%d", m_pPlayer->GetCID(), Server()->ClientName(m_pPlayer->GetCID()), m_pPlayer->GetTeam(), m_ActiveWeapon); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + } + + switch(m_ActiveWeapon) + { + case WEAPON_HAMMER: + { + GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE); + + CCharacter *apEnts[MAX_CLIENTS]; + int Hits = 0; + int Num = GameWorld()->FindEntities(ProjStartPos, GetProximityRadius()*0.5f, (CEntity**)apEnts, + MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + for(int i = 0; i < Num; ++i) + { + CCharacter *pTarget = apEnts[i]; + + if((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL)) + continue; + + // set his velocity to fast upward (for now) + if(length(pTarget->m_Pos-ProjStartPos) > 0.0f) + GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*GetProximityRadius()*0.5f); + else + GameServer()->CreateHammerHit(ProjStartPos); + + vec2 Dir; + if(length(pTarget->m_Pos - m_Pos) > 0.0f) + Dir = normalize(pTarget->m_Pos - m_Pos); + else + Dir = vec2(0.f, -1.f); + + pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, Dir*-1, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, + m_pPlayer->GetCID(), m_ActiveWeapon); + Hits++; + } + + // if we Hit anything, we have to wait for the reload + if(Hits) + m_ReloadTimer = Server()->TickSpeed()/3; + + } break; + + case WEAPON_GUN: + { + new CProjectile(GameWorld(), WEAPON_GUN, + m_pPlayer->GetCID(), + ProjStartPos, + Direction, + (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime), + g_pData->m_Weapons.m_Gun.m_pBase->m_Damage, false, 0, -1, WEAPON_GUN); + + GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE); + } break; + + case WEAPON_SHOTGUN: + { + int ShotSpread = 2; + + for(int i = -ShotSpread; i <= ShotSpread; ++i) + { + float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f}; + float a = angle(Direction); + a += Spreading[i+2]; + float v = 1-(absolute(i)/(float)ShotSpread); + float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v); + new CProjectile(GameWorld(), WEAPON_SHOTGUN, + m_pPlayer->GetCID(), + ProjStartPos, + vec2(cosf(a), sinf(a))*Speed, + (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime), + g_pData->m_Weapons.m_Shotgun.m_pBase->m_Damage, false, 0, -1, WEAPON_SHOTGUN); + } + + GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE); + } break; + + case WEAPON_GRENADE: + { + new CProjectile(GameWorld(), WEAPON_GRENADE, + m_pPlayer->GetCID(), + ProjStartPos, + Direction, + (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime), + g_pData->m_Weapons.m_Grenade.m_pBase->m_Damage, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE); + + GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE); + } break; + + case WEAPON_LASER: + { + new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID()); + GameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE); + } break; + + case WEAPON_NINJA: + { + m_NumObjectsHit = 0; + + m_Ninja.m_ActivationDir = Direction; + m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000; + m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); + + GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE); + } break; + + } + + m_AttackTick = Server()->Tick(); + + if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited + m_aWeapons[m_ActiveWeapon].m_Ammo--; + + if(!m_ReloadTimer) + m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000; +} + +void CCharacter::HandleWeapons() +{ + //ninja + HandleNinja(); + + // check reload timer + if(m_ReloadTimer) + { + m_ReloadTimer--; + return; + } + + // fire Weapon, if wanted + FireWeapon(); + + // ammo regen + int AmmoRegenTime = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Ammoregentime; + if(AmmoRegenTime && m_aWeapons[m_ActiveWeapon].m_Ammo >= 0) + { + // If equipped and not active, regen ammo? + if(m_ReloadTimer <= 0) + { + if(m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart < 0) + m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = Server()->Tick(); + + if((Server()->Tick() - m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart) >= AmmoRegenTime * Server()->TickSpeed() / 1000) + { + // Add some ammo + m_aWeapons[m_ActiveWeapon].m_Ammo = minimum(m_aWeapons[m_ActiveWeapon].m_Ammo + 1, + g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Maxammo); + m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; + } + } + else + { + m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; + } + } + + return; +} + +bool CCharacter::GiveWeapon(int Weapon, int Ammo) +{ + if(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got) + { + m_aWeapons[Weapon].m_Got = true; + m_aWeapons[Weapon].m_Ammo = minimum(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo); + return true; + } + return false; +} + +void CCharacter::GiveNinja() +{ + m_Ninja.m_ActivationTick = Server()->Tick(); + m_aWeapons[WEAPON_NINJA].m_Got = true; + m_aWeapons[WEAPON_NINJA].m_Ammo = -1; + if(m_ActiveWeapon != WEAPON_NINJA) + m_LastWeapon = m_ActiveWeapon; + m_ActiveWeapon = WEAPON_NINJA; + + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_NINJA); +} + +void CCharacter::SetEmote(int Emote, int Tick) +{ + m_EmoteType = Emote; + m_EmoteStop = Tick; +} + +void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput) +{ + // check for changes + if(mem_comp(&m_Input, pNewInput, sizeof(CNetObj_PlayerInput)) != 0) + m_LastAction = Server()->Tick(); + + // copy new input + mem_copy(&m_Input, pNewInput, sizeof(m_Input)); + m_NumInputs++; + + // it is not allowed to aim in the center + if(m_Input.m_TargetX == 0 && m_Input.m_TargetY == 0) + m_Input.m_TargetY = -1; +} + +void CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput) +{ + mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); + mem_copy(&m_LatestInput, pNewInput, sizeof(m_LatestInput)); + + // it is not allowed to aim in the center + if(m_LatestInput.m_TargetX == 0 && m_LatestInput.m_TargetY == 0) + m_LatestInput.m_TargetY = -1; + + if(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS) + { + HandleWeaponSwitch(); + FireWeapon(); + } + + mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); +} + +void CCharacter::ResetInput() +{ + m_Input.m_Direction = 0; + m_Input.m_Hook = 0; + // simulate releasing the fire button + if((m_Input.m_Fire&1) != 0) + m_Input.m_Fire++; + m_Input.m_Fire &= INPUT_STATE_MASK; + m_Input.m_Jump = 0; + m_LatestPrevInput = m_LatestInput = m_Input; +} + +void CCharacter::Tick() +{ + m_Core.m_Input = m_Input; + m_Core.Tick(true); + + // handle leaving gamelayer + if(GameLayerClipped(m_Pos)) + { + Die(m_pPlayer->GetCID(), WEAPON_WORLD); + } + + // handle Weapons + HandleWeapons(); +} + +void CCharacter::TickDefered() +{ + static const vec2 ColBox(CCharacterCore::PHYS_SIZE, CCharacterCore::PHYS_SIZE); + // advance the dummy + { + CWorldCore TempWorld; + m_ReckoningCore.Init(&TempWorld, GameServer()->Collision()); + m_ReckoningCore.Tick(false); + m_ReckoningCore.Move(); + m_ReckoningCore.Quantize(); + } + + // apply drag velocity when the player is not firing ninja + // and set it back to 0 for the next tick + if(m_ActiveWeapon != WEAPON_NINJA || m_Ninja.m_CurrentMoveTime < 0) + m_Core.AddDragVelocity(); + m_Core.ResetDragVelocity(); + + //lastsentcore + vec2 StartPos = m_Core.m_Pos; + vec2 StartVel = m_Core.m_Vel; + bool StuckBefore = GameServer()->Collision()->TestBox(m_Core.m_Pos, ColBox); + + m_Core.Move(); + + bool StuckAfterMove = GameServer()->Collision()->TestBox(m_Core.m_Pos, ColBox); + m_Core.Quantize(); + bool StuckAfterQuant = GameServer()->Collision()->TestBox(m_Core.m_Pos, ColBox); + m_Pos = m_Core.m_Pos; + + if(!StuckBefore && (StuckAfterMove || StuckAfterQuant)) + { + // Hackish solution to get rid of strict-aliasing warning + union + { + float f; + unsigned u; + }StartPosX, StartPosY, StartVelX, StartVelY; + + StartPosX.f = StartPos.x; + StartPosY.f = StartPos.y; + StartVelX.f = StartVel.x; + StartVelY.f = StartVel.y; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", + StuckBefore, + StuckAfterMove, + StuckAfterQuant, + StartPos.x, StartPos.y, + StartVel.x, StartVel.y, + StartPosX.u, StartPosY.u, + StartVelX.u, StartVelY.u); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + } + + m_TriggeredEvents |= m_Core.m_TriggeredEvents; + + if(m_pPlayer->GetTeam() == TEAM_SPECTATORS) + { + m_Pos.x = m_Input.m_TargetX; + m_Pos.y = m_Input.m_TargetY; + } + else if(m_Core.m_Death) + { + // handle death-tiles + Die(m_pPlayer->GetCID(), WEAPON_WORLD); + } + + // update the m_SendCore if needed + { + CNetObj_Character Predicted; + CNetObj_Character Current; + mem_zero(&Predicted, sizeof(Predicted)); + mem_zero(&Current, sizeof(Current)); + m_ReckoningCore.Write(&Predicted); + m_Core.Write(&Current); + + // only allow dead reackoning for a top of 3 seconds + if(m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) + { + m_ReckoningTick = Server()->Tick(); + m_SendCore = m_Core; + m_ReckoningCore = m_Core; + } + } +} + +void CCharacter::TickPaused() +{ + ++m_AttackTick; + ++m_Ninja.m_ActivationTick; + ++m_ReckoningTick; + if(m_LastAction != -1) + ++m_LastAction; + if(m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart > -1) + ++m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart; + if(m_EmoteStop > -1) + ++m_EmoteStop; +} + +bool CCharacter::IncreaseHealth(int Amount) +{ + if(m_Health >= 10) + return false; + m_Health = clamp(m_Health+Amount, 0, 10); + return true; +} + +bool CCharacter::IncreaseArmor(int Amount) +{ + if(m_Armor >= 10) + return false; + m_Armor = clamp(m_Armor+Amount, 0, 10); + return true; +} + +void CCharacter::Die(int Killer, int Weapon) +{ + // we got to wait 0.5 secs before respawning + m_Alive = false; + m_pPlayer->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; + int ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, (Killer < 0) ? 0 : GameServer()->m_apPlayers[Killer], Weapon); + + char aBuf[256]; + if(Killer < 0) + { + str_format(aBuf, sizeof(aBuf), "kill killer='%d:%d:' victim='%d:%d:%s' weapon=%d special=%d", + Killer, - 1 - Killer, + m_pPlayer->GetCID(), m_pPlayer->GetTeam(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial + ); + } + else + { + str_format(aBuf, sizeof(aBuf), "kill killer='%d:%d:%s' victim='%d:%d:%s' weapon=%d special=%d", + Killer, GameServer()->m_apPlayers[Killer]->GetTeam(), Server()->ClientName(Killer), + m_pPlayer->GetCID(), m_pPlayer->GetTeam(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial + ); + } + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + + // send the kill message + CNetMsg_Sv_KillMsg Msg; + Msg.m_Victim = m_pPlayer->GetCID(); + Msg.m_ModeSpecial = ModeSpecial; + for(int i = 0 ; i < MAX_CLIENTS; i++) + { + if(!Server()->ClientIngame(i)) + continue; + + if(Killer < 0 && Server()->GetClientVersion(i) < MIN_KILLMESSAGE_CLIENTVERSION) + { + Msg.m_Killer = 0; + Msg.m_Weapon = WEAPON_WORLD; + } + else + { + Msg.m_Killer = Killer; + Msg.m_Weapon = Weapon; + } + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, i); + } + + // a nice sound + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE); + + // this is for auto respawn after 3 secs + m_pPlayer->m_DieTick = Server()->Tick(); + + GameWorld()->RemoveEntity(this); + GameWorld()->m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; + GameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID()); +} + +bool CCharacter::TakeDamage(vec2 Force, vec2 Source, int Dmg, int From, int Weapon) +{ + m_Core.m_Vel += Force; + + if(From >= 0) + { + if(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From)) + return false; + } + else + { + int Team = TEAM_RED; + if(From == PLAYER_TEAM_BLUE) + Team = TEAM_BLUE; + if(GameServer()->m_pController->IsFriendlyTeamFire(m_pPlayer->GetTeam(), Team)) + return false; + } + + // m_pPlayer only inflicts half damage on self + if(From == m_pPlayer->GetCID()) + Dmg = maximum(1, Dmg/2); + + int OldHealth = m_Health, OldArmor = m_Armor; + if(Dmg) + { + if(m_Armor) + { + if(Dmg > 1) + { + m_Health--; + Dmg--; + } + + if(Dmg > m_Armor) + { + Dmg -= m_Armor; + m_Armor = 0; + } + else + { + m_Armor -= Dmg; + Dmg = 0; + } + } + + m_Health -= Dmg; + } + + // create healthmod indicator + GameServer()->CreateDamage(m_Pos, m_pPlayer->GetCID(), Source, OldHealth-m_Health, OldArmor-m_Armor, From == m_pPlayer->GetCID()); + + // do damage Hit sound + if(From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) + { + int64 Mask = CmaskOne(From); + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i] && (GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || GameServer()->m_apPlayers[i]->m_DeadSpecMode) && + GameServer()->m_apPlayers[i]->GetSpectatorID() == From) + Mask |= CmaskOne(i); + } + GameServer()->CreateSound(GameServer()->m_apPlayers[From]->m_ViewPos, SOUND_HIT, Mask); + } + + // check for death + if(m_Health <= 0) + { + Die(From, Weapon); + + // set attacker's face to happy (taunt!) + if(From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) + { + CCharacter *pChr = GameServer()->m_apPlayers[From]->GetCharacter(); + if(pChr) + { + pChr->SetEmote(EMOTE_HAPPY, Server()->Tick() + Server()->TickSpeed()); + } + } + + return false; + } + + if(Dmg > 2) + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG); + else + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT); + + SetEmote(EMOTE_PAIN, Server()->Tick() + 500 * Server()->TickSpeed() / 1000); + + return true; +} + +void CCharacter::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient)) + return; + + CNetObj_Character *pCharacter = static_cast(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, m_pPlayer->GetCID(), sizeof(CNetObj_Character))); + if(!pCharacter) + return; + + // write down the m_Core + if(!m_ReckoningTick || GameWorld()->m_Paused) + { + // no dead reckoning when paused because the client doesn't know + // how far to perform the reckoning + pCharacter->m_Tick = 0; + m_Core.Write(pCharacter); + } + else + { + pCharacter->m_Tick = m_ReckoningTick; + m_SendCore.Write(pCharacter); + } + + // set emote + if(m_EmoteStop < Server()->Tick()) + { + SetEmote(EMOTE_NORMAL, -1); + } + + pCharacter->m_Emote = m_EmoteType; + + pCharacter->m_AmmoCount = 0; + pCharacter->m_Health = 0; + pCharacter->m_Armor = 0; + pCharacter->m_TriggeredEvents = m_TriggeredEvents; + + pCharacter->m_Weapon = m_ActiveWeapon; + pCharacter->m_AttackTick = m_AttackTick; + + pCharacter->m_Direction = m_Input.m_Direction; + + if(m_pPlayer->GetCID() == SnappingClient || SnappingClient == -1 || + (!Config()->m_SvStrictSpectateMode && m_pPlayer->GetCID() == GameServer()->m_apPlayers[SnappingClient]->GetSpectatorID())) + { + pCharacter->m_Health = m_Health; + pCharacter->m_Armor = m_Armor; + if(m_ActiveWeapon == WEAPON_NINJA) + pCharacter->m_AmmoCount = m_Ninja.m_ActivationTick + g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000; + else if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) + pCharacter->m_AmmoCount = m_aWeapons[m_ActiveWeapon].m_Ammo; + } + + if(pCharacter->m_Emote == EMOTE_NORMAL) + { + if(5 * Server()->TickSpeed() - ((Server()->Tick() - m_LastAction) % (5 * Server()->TickSpeed())) < 5) + pCharacter->m_Emote = EMOTE_BLINK; + } +} + +void CCharacter::PostSnap() +{ + m_TriggeredEvents = 0; +} diff --git a/src/game/server/entities/character.h b/src/game/server/entities/character.h new file mode 100644 index 000000000..c1c8b9443 --- /dev/null +++ b/src/game/server/entities/character.h @@ -0,0 +1,131 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_CHARACTER_H +#define GAME_SERVER_ENTITIES_CHARACTER_H + +#include + +#include +#include + + +class CCharacter : public CEntity +{ + MACRO_ALLOC_POOL_ID() + +public: + //character's size + static const int ms_PhysSize = 28; + + enum + { + MIN_KILLMESSAGE_CLIENTVERSION=0x0704, // todo 0.8: remove me + }; + + CCharacter(CGameWorld *pWorld); + + virtual void Reset(); + virtual void Destroy(); + virtual void Tick(); + virtual void TickDefered(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + virtual void PostSnap(); + + bool IsGrounded(); + + void SetWeapon(int W); + void HandleWeaponSwitch(); + void DoWeaponSwitch(); + + void HandleWeapons(); + void HandleNinja(); + + void OnPredictedInput(CNetObj_PlayerInput *pNewInput); + void OnDirectInput(CNetObj_PlayerInput *pNewInput); + void ResetInput(); + void FireWeapon(); + + void Die(int Killer, int Weapon); + bool TakeDamage(vec2 Force, vec2 Source, int Dmg, int From, int Weapon); + + bool Spawn(class CPlayer *pPlayer, vec2 Pos); + bool Remove(); + + bool IncreaseHealth(int Amount); + bool IncreaseArmor(int Amount); + + bool GiveWeapon(int Weapon, int Ammo); + void GiveNinja(); + + void SetEmote(int Emote, int Tick); + + bool IsAlive() const { return m_Alive; } + class CPlayer *GetPlayer() { return m_pPlayer; } + +private: + // player controlling this character + class CPlayer *m_pPlayer; + + bool m_Alive; + + // weapon info + CEntity *m_apHitObjects[MAX_PLAYERS]; + int m_NumObjectsHit; + + struct WeaponStat + { + int m_AmmoRegenStart; + int m_Ammo; + bool m_Got; + + } m_aWeapons[NUM_WEAPONS]; + + int m_ActiveWeapon; + int m_LastWeapon; + int m_QueuedWeapon; + + int m_ReloadTimer; + int m_AttackTick; + + int m_EmoteType; + int m_EmoteStop; + + // last tick that the player took any action ie some input + int m_LastAction; + int m_LastNoAmmoSound; + + // these are non-heldback inputs + CNetObj_PlayerInput m_LatestPrevInput; + CNetObj_PlayerInput m_LatestInput; + + // input + CNetObj_PlayerInput m_Input; + int m_NumInputs; + int m_Jumped; + + int m_Health; + int m_Armor; + + int m_TriggeredEvents; + + // ninja + struct + { + vec2 m_ActivationDir; + int m_ActivationTick; + int m_CurrentMoveTime; + int m_OldVelAmount; + } m_Ninja; + + // the player core for the physics + CCharacterCore m_Core; + + // info for dead reckoning + int m_ReckoningTick; // tick that we are performing dead reckoning From + CCharacterCore m_SendCore; // core that we should send + CCharacterCore m_ReckoningCore; // the dead reckoning core + +}; + +#endif diff --git a/src/game/server/entities/flag.cpp b/src/game/server/entities/flag.cpp new file mode 100644 index 000000000..99bf05da0 --- /dev/null +++ b/src/game/server/entities/flag.cpp @@ -0,0 +1,96 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include "character.h" +#include "flag.h" + +CFlag::CFlag(CGameWorld *pGameWorld, int Team, vec2 StandPos) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_FLAG, StandPos, ms_PhysSize) +{ + m_Team = Team; + m_StandPos = StandPos; + + GameWorld()->InsertEntity(this); + + Reset(); +} + +void CFlag::Reset() +{ + m_pCarrier = 0; + m_AtStand = true; + m_Pos = m_StandPos; + m_Vel = vec2(0, 0); + m_GrabTick = 0; +} + +void CFlag::Grab(CCharacter *pChar) +{ + m_pCarrier = pChar; + if(m_AtStand) + m_GrabTick = Server()->Tick(); + m_AtStand = false; +} + +void CFlag::Drop() +{ + m_pCarrier = 0; + m_Vel = vec2(0, 0); + m_DropTick = Server()->Tick(); +} + +void CFlag::TickDefered() +{ + if(m_pCarrier) + { + // update flag position + m_Pos = m_pCarrier->GetPos(); + } + else + { + // flag hits death-tile or left the game layer, reset it + if((GameServer()->Collision()->GetCollisionAt(m_Pos.x, m_Pos.y) & CCollision::COLFLAG_DEATH) + || GameLayerClipped(m_Pos)) + { + Reset(); + GameServer()->m_pController->OnFlagReturn(this); + } + + if(!m_AtStand) + { + if(Server()->Tick() > m_DropTick + Server()->TickSpeed()*30) + { + Reset(); + GameServer()->m_pController->OnFlagReturn(this); + } + else + { + m_Vel.y += GameWorld()->m_Core.m_Tuning.m_Gravity; + GameServer()->Collision()->MoveBox(&m_Pos, &m_Vel, vec2(ms_PhysSize, ms_PhysSize), 0.5f); + } + } + } +} + +void CFlag::TickPaused() +{ + m_DropTick++; + if(m_GrabTick) + m_GrabTick++; +} + +void CFlag::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient)) + return; + + CNetObj_Flag *pFlag = (CNetObj_Flag *)Server()->SnapNewItem(NETOBJTYPE_FLAG, m_Team, sizeof(CNetObj_Flag)); + if(!pFlag) + return; + + pFlag->m_X = round_to_int(m_Pos.x); + pFlag->m_Y = round_to_int(m_Pos.y); + pFlag->m_Team = m_Team; +} diff --git a/src/game/server/entities/flag.h b/src/game/server/entities/flag.h new file mode 100644 index 000000000..df1bae62a --- /dev/null +++ b/src/game/server/entities/flag.h @@ -0,0 +1,47 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_FLAG_H +#define GAME_SERVER_ENTITIES_FLAG_H + +#include + +class CFlag : public CEntity +{ +private: + /* Identity */ + int m_Team; + vec2 m_StandPos; + + /* State */ + bool m_AtStand; + CCharacter *m_pCarrier; + vec2 m_Vel; + int m_GrabTick; + int m_DropTick; + +public: + /* Constants */ + static int const ms_PhysSize = 14; + + /* Constructor */ + CFlag(CGameWorld *pGameWorld, int Team, vec2 StandPos); + + /* Getters */ + int GetTeam() const { return m_Team; } + bool IsAtStand() const { return m_AtStand; } + CCharacter *GetCarrier() const { return m_pCarrier; } + int GetGrabTick() const { return m_GrabTick; } + int GetDropTick() const { return m_DropTick; } + + /* CEntity functions */ + virtual void Reset(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + virtual void TickDefered(); + + /* Functions */ + void Grab(class CCharacter *pChar); + void Drop(); +}; + +#endif diff --git a/src/game/server/entities/laser.cpp b/src/game/server/entities/laser.cpp new file mode 100644 index 000000000..8bc9194cd --- /dev/null +++ b/src/game/server/entities/laser.cpp @@ -0,0 +1,114 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include "character.h" +#include "laser.h" + +CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER, Pos) +{ + m_Owner = Owner; + m_Energy = StartEnergy; + m_Dir = Direction; + m_Bounces = 0; + m_EvalTick = 0; + GameWorld()->InsertEntity(this); + DoBounce(); +} + + +bool CLaser::HitCharacter(vec2 From, vec2 To) +{ + vec2 At; + CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + CCharacter *pHit = GameWorld()->IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar); + if(!pHit) + return false; + + m_From = From; + m_Pos = At; + m_Energy = -1; + pHit->TakeDamage(vec2(0.f, 0.f), normalize(To-From), g_pData->m_Weapons.m_aId[WEAPON_LASER].m_Damage, m_Owner, WEAPON_LASER); + return true; +} + +void CLaser::DoBounce() +{ + m_EvalTick = Server()->Tick(); + + if(m_Energy < 0) + { + GameWorld()->DestroyEntity(this); + return; + } + + vec2 To = m_Pos + m_Dir * m_Energy; + + if(GameServer()->Collision()->IntersectLine(m_Pos, To, 0x0, &To)) + { + if(!HitCharacter(m_Pos, To)) + { + // intersected + m_From = m_Pos; + m_Pos = To; + + vec2 TempPos = m_Pos; + vec2 TempDir = m_Dir * 4.0f; + + GameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0); + m_Pos = TempPos; + m_Dir = normalize(TempDir); + + m_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost; + m_Bounces++; + + if(m_Bounces > GameServer()->Tuning()->m_LaserBounceNum) + m_Energy = -1; + + GameServer()->CreateSound(m_Pos, SOUND_LASER_BOUNCE); + } + } + else + { + if(!HitCharacter(m_Pos, To)) + { + m_From = m_Pos; + m_Pos = To; + m_Energy = -1; + } + } +} + +void CLaser::Reset() +{ + GameWorld()->DestroyEntity(this); +} + +void CLaser::Tick() +{ + if((Server()->Tick() - m_EvalTick) > (Server()->TickSpeed()*GameServer()->Tuning()->m_LaserBounceDelay)/1000.0f) + DoBounce(); +} + +void CLaser::TickPaused() +{ + ++m_EvalTick; +} + +void CLaser::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient) && NetworkClipped(SnappingClient, m_From)) + return; + + CNetObj_Laser *pObj = static_cast(Server()->SnapNewItem(NETOBJTYPE_LASER, GetID(), sizeof(CNetObj_Laser))); + if(!pObj) + return; + + pObj->m_X = round_to_int(m_Pos.x); + pObj->m_Y = round_to_int(m_Pos.y); + pObj->m_FromX = round_to_int(m_From.x); + pObj->m_FromY = round_to_int(m_From.y); + pObj->m_StartTick = m_EvalTick; +} diff --git a/src/game/server/entities/laser.h b/src/game/server/entities/laser.h new file mode 100644 index 000000000..8ae6f7924 --- /dev/null +++ b/src/game/server/entities/laser.h @@ -0,0 +1,31 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_LASER_H +#define GAME_SERVER_ENTITIES_LASER_H + +#include + +class CLaser : public CEntity +{ +public: + CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +protected: + bool HitCharacter(vec2 From, vec2 To); + void DoBounce(); + +private: + vec2 m_From; + vec2 m_Dir; + float m_Energy; + int m_Bounces; + int m_EvalTick; + int m_Owner; +}; + +#endif diff --git a/src/game/server/entities/pickup.cpp b/src/game/server/entities/pickup.cpp new file mode 100644 index 000000000..c11fc5c3f --- /dev/null +++ b/src/game/server/entities/pickup.cpp @@ -0,0 +1,149 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include +#include + +#include "character.h" +#include "pickup.h" + +CPickup::CPickup(CGameWorld *pGameWorld, int Type, vec2 Pos) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP, Pos, PickupPhysSize) +{ + m_Type = Type; + + Reset(); + + GameWorld()->InsertEntity(this); +} + +void CPickup::Reset() +{ + if (g_pData->m_aPickups[m_Type].m_Spawndelay > 0) + m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * g_pData->m_aPickups[m_Type].m_Spawndelay; + else + m_SpawnTick = -1; +} + +void CPickup::Tick() +{ + // wait for respawn + if(m_SpawnTick > 0) + { + if(Server()->Tick() > m_SpawnTick) + { + // respawn + m_SpawnTick = -1; + + if(m_Type == PICKUP_GRENADE || m_Type == PICKUP_SHOTGUN || m_Type == PICKUP_LASER) + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN); + } + else + return; + } + // Check if a player intersected us + CCharacter *pChr = (CCharacter *)GameWorld()->ClosestEntity(m_Pos, 20.0f, CGameWorld::ENTTYPE_CHARACTER, 0); + if(pChr && pChr->IsAlive()) + { + // player picked us up, is someone was hooking us, let them go + bool Picked = false; + switch (m_Type) + { + case PICKUP_HEALTH: + if(pChr->IncreaseHealth(1)) + { + Picked = true; + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH); + } + break; + + case PICKUP_ARMOR: + if(pChr->IncreaseArmor(1)) + { + Picked = true; + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR); + } + break; + + case PICKUP_GRENADE: + if(pChr->GiveWeapon(WEAPON_GRENADE, g_pData->m_Weapons.m_aId[WEAPON_GRENADE].m_Maxammo)) + { + Picked = true; + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE); + if(pChr->GetPlayer()) + GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_GRENADE); + } + break; + case PICKUP_SHOTGUN: + if(pChr->GiveWeapon(WEAPON_SHOTGUN, g_pData->m_Weapons.m_aId[WEAPON_SHOTGUN].m_Maxammo)) + { + Picked = true; + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN); + if(pChr->GetPlayer()) + GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_SHOTGUN); + } + break; + case PICKUP_LASER: + if(pChr->GiveWeapon(WEAPON_LASER, g_pData->m_Weapons.m_aId[WEAPON_LASER].m_Maxammo)) + { + Picked = true; + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN); + if(pChr->GetPlayer()) + GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_LASER); + } + break; + + case PICKUP_NINJA: + { + Picked = true; + // activate ninja on target player + pChr->GiveNinja(); + + // loop through all players, setting their emotes + CCharacter *pC = static_cast(GameWorld()->FindFirst(CGameWorld::ENTTYPE_CHARACTER)); + for(; pC; pC = (CCharacter *)pC->TypeNext()) + { + if (pC != pChr) + pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed()); + } + + pChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 1200 * Server()->TickSpeed() / 1000); + break; + } + + default: + break; + }; + + if(Picked) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "pickup player='%d:%s' item=%d", + pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + int RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; + if(RespawnTime >= 0) + m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime; + } + } +} + +void CPickup::TickPaused() +{ + if(m_SpawnTick != -1) + ++m_SpawnTick; +} + +void CPickup::Snap(int SnappingClient) +{ + if(m_SpawnTick != -1 || NetworkClipped(SnappingClient)) + return; + + CNetObj_Pickup *pP = static_cast(Server()->SnapNewItem(NETOBJTYPE_PICKUP, GetID(), sizeof(CNetObj_Pickup))); + if(!pP) + return; + + pP->m_X = round_to_int(m_Pos.x); + pP->m_Y = round_to_int(m_Pos.y); + pP->m_Type = m_Type; +} diff --git a/src/game/server/entities/pickup.h b/src/game/server/entities/pickup.h new file mode 100644 index 000000000..ad518a99e --- /dev/null +++ b/src/game/server/entities/pickup.h @@ -0,0 +1,25 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_PICKUP_H +#define GAME_SERVER_ENTITIES_PICKUP_H + +#include + +const int PickupPhysSize = 14; + +class CPickup : public CEntity +{ +public: + CPickup(CGameWorld *pGameWorld, int Type, vec2 Pos); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +private: + int m_Type; + int m_SpawnTick; +}; + +#endif diff --git a/src/game/server/entities/projectile.cpp b/src/game/server/entities/projectile.cpp new file mode 100644 index 000000000..66ce52c66 --- /dev/null +++ b/src/game/server/entities/projectile.cpp @@ -0,0 +1,121 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include "character.h" +#include "projectile.h" + +CProjectile::CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span, + int Damage, bool Explosive, float Force, int SoundImpact, int Weapon) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE, vec2(round_to_int(Pos.x), round_to_int(Pos.y))) +{ + m_Type = Type; + m_Direction.x = round_to_int(Dir.x*100.0f) / 100.0f; + m_Direction.y = round_to_int(Dir.y*100.0f) / 100.0f; + m_LifeSpan = Span; + m_Owner = Owner; + m_OwnerTeam = GameServer()->m_apPlayers[Owner]->GetTeam(); + m_Force = Force; + m_Damage = Damage; + m_SoundImpact = SoundImpact; + m_Weapon = Weapon; + m_StartTick = Server()->Tick(); + m_Explosive = Explosive; + + GameWorld()->InsertEntity(this); +} + +void CProjectile::Reset() +{ + GameWorld()->DestroyEntity(this); +} + +void CProjectile::LoseOwner() +{ + if(m_OwnerTeam == TEAM_BLUE) + m_Owner = PLAYER_TEAM_BLUE; + else + m_Owner = PLAYER_TEAM_RED; +} + +vec2 CProjectile::GetPos(float Time) +{ + float Curvature = 0; + float Speed = 0; + + switch(m_Type) + { + case WEAPON_GRENADE: + Curvature = GameServer()->Tuning()->m_GrenadeCurvature; + Speed = GameServer()->Tuning()->m_GrenadeSpeed; + break; + + case WEAPON_SHOTGUN: + Curvature = GameServer()->Tuning()->m_ShotgunCurvature; + Speed = GameServer()->Tuning()->m_ShotgunSpeed; + break; + + case WEAPON_GUN: + Curvature = GameServer()->Tuning()->m_GunCurvature; + Speed = GameServer()->Tuning()->m_GunSpeed; + break; + } + + return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); +} + + +void CProjectile::Tick() +{ + float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed(); + float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + vec2 PrevPos = GetPos(Pt); + vec2 CurPos = GetPos(Ct); + int Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &CurPos, 0); + CCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner); + CCharacter *TargetChr = GameWorld()->IntersectCharacter(PrevPos, CurPos, 6.0f, CurPos, OwnerChar); + + m_LifeSpan--; + + if(TargetChr || Collide || m_LifeSpan < 0 || GameLayerClipped(CurPos)) + { + if(m_LifeSpan >= 0 || m_Weapon == WEAPON_GRENADE) + GameServer()->CreateSound(CurPos, m_SoundImpact); + + if(m_Explosive) + GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, m_Damage); + + else if(TargetChr) + TargetChr->TakeDamage(m_Direction * maximum(0.001f, m_Force), m_Direction*-1, m_Damage, m_Owner, m_Weapon); + + GameWorld()->DestroyEntity(this); + } +} + +void CProjectile::TickPaused() +{ + ++m_StartTick; +} + +void CProjectile::FillInfo(CNetObj_Projectile *pProj) +{ + pProj->m_X = round_to_int(m_Pos.x); + pProj->m_Y = round_to_int(m_Pos.y); + pProj->m_VelX = round_to_int(m_Direction.x*100.0f); + pProj->m_VelY = round_to_int(m_Direction.y*100.0f); + pProj->m_StartTick = m_StartTick; + pProj->m_Type = m_Type; +} + +void CProjectile::Snap(int SnappingClient) +{ + float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + + if(NetworkClipped(SnappingClient, GetPos(Ct))) + return; + + CNetObj_Projectile *pProj = static_cast(Server()->SnapNewItem(NETOBJTYPE_PROJECTILE, GetID(), sizeof(CNetObj_Projectile))); + if(pProj) + FillInfo(pProj); +} diff --git a/src/game/server/entities/projectile.h b/src/game/server/entities/projectile.h new file mode 100644 index 000000000..284d358ad --- /dev/null +++ b/src/game/server/entities/projectile.h @@ -0,0 +1,45 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_PROJECTILE_H +#define GAME_SERVER_ENTITIES_PROJECTILE_H + +#include + +enum +{ + PLAYER_TEAM_BLUE = -2, + PLAYER_TEAM_RED = -1 +}; + +class CProjectile : public CEntity +{ +public: + CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span, + int Damage, bool Explosive, float Force, int SoundImpact, int Weapon); + + vec2 GetPos(float Time); + void FillInfo(CNetObj_Projectile *pProj); + + int GetOwner() const { return m_Owner; } + void LoseOwner(); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +private: + vec2 m_Direction; + int m_LifeSpan; + int m_Owner; + int m_OwnerTeam; + int m_Type; + int m_Damage; + int m_SoundImpact; + int m_Weapon; + float m_Force; + int m_StartTick; + bool m_Explosive; +}; + +#endif diff --git a/src/game/server/entity.cpp b/src/game/server/entity.cpp new file mode 100644 index 000000000..a9c54eb8e --- /dev/null +++ b/src/game/server/entity.cpp @@ -0,0 +1,57 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "entity.h" +#include "gamecontext.h" +#include "player.h" + +CEntity::CEntity(CGameWorld *pGameWorld, int ObjType, vec2 Pos, int ProximityRadius) +{ + m_pGameWorld = pGameWorld; + + m_pPrevTypeEntity = 0; + m_pNextTypeEntity = 0; + + m_ID = Server()->SnapNewID(); + m_ObjType = ObjType; + + m_ProximityRadius = ProximityRadius; + + m_MarkedForDestroy = false; + m_Pos = Pos; +} + +CEntity::~CEntity() +{ + GameWorld()->RemoveEntity(this); + Server()->SnapFreeID(m_ID); +} + +int CEntity::NetworkClipped(int SnappingClient) +{ + return NetworkClipped(SnappingClient, m_Pos); +} + +int CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos) +{ + if(SnappingClient == -1) + return 0; + + float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x; + float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y; + + if(absolute(dx) > 1000.0f || absolute(dy) > 800.0f) + return 1; + + if(distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, CheckPos) > 1100.0f) + return 1; + return 0; +} + +bool CEntity::GameLayerClipped(vec2 CheckPos) +{ + int rx = round_to_int(CheckPos.x) / 32; + int ry = round_to_int(CheckPos.y) / 32; + return (rx < -200 || rx >= GameServer()->Collision()->GetWidth()+200) + || (ry < -200 || ry >= GameServer()->Collision()->GetHeight()+200); +} diff --git a/src/game/server/entity.h b/src/game/server/entity.h new file mode 100644 index 000000000..12c63cc4c --- /dev/null +++ b/src/game/server/entity.h @@ -0,0 +1,145 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITY_H +#define GAME_SERVER_ENTITY_H + +#include + +#include "alloc.h" +#include "gameworld.h" + +/* + Class: Entity + Basic entity class. +*/ +class CEntity +{ + MACRO_ALLOC_HEAP() + +private: + /* Friend classes */ + friend class CGameWorld; // for entity list handling + + /* Identity */ + class CGameWorld *m_pGameWorld; + + CEntity *m_pPrevTypeEntity; + CEntity *m_pNextTypeEntity; + + int m_ID; + int m_ObjType; + + /* + Variable: m_ProximityRadius + Contains the physical size of the entity. + */ + float m_ProximityRadius; + + /* State */ + bool m_MarkedForDestroy; + +protected: + /* State */ + + /* + Variable: m_Pos + Contains the current posititon of the entity. + */ + vec2 m_Pos; + + /* Getters */ + int GetID() const { return m_ID; } + +public: + /* Constructor */ + CEntity(CGameWorld *pGameWorld, int Objtype, vec2 Pos, int ProximityRadius=0); + + /* Destructor */ + virtual ~CEntity(); + + /* Objects */ + class CGameWorld *GameWorld() { return m_pGameWorld; } + class CConfig *Config() { return m_pGameWorld->Config(); } + class CGameContext *GameServer() { return m_pGameWorld->GameServer(); } + class IServer *Server() { return m_pGameWorld->Server(); } + + /* Getters */ + CEntity *TypeNext() { return m_pNextTypeEntity; } + CEntity *TypePrev() { return m_pPrevTypeEntity; } + const vec2 &GetPos() const { return m_Pos; } + float GetProximityRadius() const { return m_ProximityRadius; } + bool IsMarkedForDestroy() const { return m_MarkedForDestroy; } + + /* Setters */ + void MarkForDestroy() { m_MarkedForDestroy = true; } + + /* Other functions */ + + /* + Function: Destroy + Destroys the entity. + */ + virtual void Destroy() { delete this; } + + /* + Function: Reset + Called when the game resets the map. Puts the entity + back to its starting state or perhaps destroys it. + */ + virtual void Reset() {} + + /* + Function: Tick + Called to progress the entity to the next tick. Updates + and moves the entity to its new state and position. + */ + virtual void Tick() {} + + /* + Function: TickDefered + Called after all entities Tick() function has been called. + */ + virtual void TickDefered() {} + + /* + Function: TickPaused + Called when the game is paused, to freeze the state and position of the entity. + */ + virtual void TickPaused() {} + + /* + Function: Snap + Called when a new snapshot is being generated for a specific + client. + + Arguments: + SnappingClient - ID of the client which snapshot is + being generated. Could be -1 to create a complete + snapshot of everything in the game for demo + recording. + */ + virtual void Snap(int SnappingClient) {} + + virtual void PostSnap() {} + + /* + Function: networkclipped(int snapping_client) + Performs a series of test to see if a client can see the + entity. + + Arguments: + SnappingClient - ID of the client which snapshot is + being generated. Could be -1 to create a complete + snapshot of everything in the game for demo + recording. + + Returns: + Non-zero if the entity doesn't have to be in the snapshot. + */ + int NetworkClipped(int SnappingClient); + int NetworkClipped(int SnappingClient, vec2 CheckPos); + + bool GameLayerClipped(vec2 CheckPos); +}; + +#endif diff --git a/src/game/server/eventhandler.cpp b/src/game/server/eventhandler.cpp new file mode 100644 index 000000000..69cb721bd --- /dev/null +++ b/src/game/server/eventhandler.cpp @@ -0,0 +1,60 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include "eventhandler.h" +#include "gamecontext.h" +#include "player.h" + +////////////////////////////////////////////////// +// Event handler +////////////////////////////////////////////////// +CEventHandler::CEventHandler() +{ + m_pGameServer = 0; + Clear(); +} + +void CEventHandler::SetGameServer(CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; +} + +void *CEventHandler::Create(int Type, int Size, int64 Mask) +{ + if(m_NumEvents == MAX_EVENTS) + return 0; + if(m_CurrentOffset+Size >= MAX_DATASIZE) + return 0; + + void *p = &m_aData[m_CurrentOffset]; + m_aOffsets[m_NumEvents] = m_CurrentOffset; + m_aTypes[m_NumEvents] = Type; + m_aSizes[m_NumEvents] = Size; + m_aClientMasks[m_NumEvents] = Mask; + m_CurrentOffset += Size; + m_NumEvents++; + return p; +} + +void CEventHandler::Clear() +{ + m_NumEvents = 0; + m_CurrentOffset = 0; +} + +void CEventHandler::Snap(int SnappingClient) +{ + for(int i = 0; i < m_NumEvents; i++) + { + if(SnappingClient == -1 || CmaskIsSet(m_aClientMasks[i], SnappingClient)) + { + CNetEvent_Common *ev = (CNetEvent_Common *)&m_aData[m_aOffsets[i]]; + if(SnappingClient == -1 || distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, vec2(ev->m_X, ev->m_Y)) < 1500.0f) + { + void *d = GameServer()->Server()->SnapNewItem(m_aTypes[i], i, m_aSizes[i]); + if(d) + mem_copy(d, &m_aData[m_aOffsets[i]], m_aSizes[i]); + } + } + } +} diff --git a/src/game/server/eventhandler.h b/src/game/server/eventhandler.h new file mode 100644 index 000000000..fc9219735 --- /dev/null +++ b/src/game/server/eventhandler.h @@ -0,0 +1,32 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_EVENTHANDLER_H +#define GAME_SERVER_EVENTHANDLER_H + +// +class CEventHandler +{ + static const int MAX_EVENTS = 128; + static const int MAX_DATASIZE = 128*64; + + int m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays + int m_aOffsets[MAX_EVENTS]; + int m_aSizes[MAX_EVENTS]; + int64 m_aClientMasks[MAX_EVENTS]; + char m_aData[MAX_DATASIZE]; + + class CGameContext *m_pGameServer; + + int m_CurrentOffset; + int m_NumEvents; +public: + CGameContext *GameServer() const { return m_pGameServer; } + void SetGameServer(CGameContext *pGameServer); + + CEventHandler(); + void *Create(int Type, int Size, int64 Mask = -1); + void Clear(); + void Snap(int SnappingClient); +}; + +#endif diff --git a/src/game/server/gamecontext.cpp b/src/game/server/gamecontext.cpp new file mode 100644 index 000000000..878b84763 --- /dev/null +++ b/src/game/server/gamecontext.cpp @@ -0,0 +1,1734 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "entities/character.h" +#include "entities/projectile.h" +#include "gamemodes/ctf.h" +#include "gamemodes/dm.h" +#include "gamemodes/lms.h" +#include "gamemodes/lts.h" +#include "gamemodes/mod.h" +#include "gamemodes/tdm.h" +#include "gamecontext.h" +#include "player.h" + +enum +{ + RESET, + NO_RESET +}; + +void CGameContext::Construct(int Resetting) +{ + m_Resetting = 0; + m_pServer = 0; + + for(int i = 0; i < MAX_CLIENTS; i++) + m_apPlayers[i] = 0; + + m_pController = 0; + m_VoteCloseTime = 0; + m_VoteCancelTime = 0; + m_pVoteOptionFirst = 0; + m_pVoteOptionLast = 0; + m_NumVoteOptions = 0; + m_LockTeams = 0; + + if(Resetting==NO_RESET) + m_pVoteOptionHeap = new CHeap(); +} + +CGameContext::CGameContext(int Resetting) +{ + Construct(Resetting); +} + +CGameContext::CGameContext() +{ + Construct(NO_RESET); +} + +CGameContext::~CGameContext() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + delete m_apPlayers[i]; + if(!m_Resetting) + delete m_pVoteOptionHeap; +} + +void CGameContext::Clear() +{ + CHeap *pVoteOptionHeap = m_pVoteOptionHeap; + CVoteOptionServer *pVoteOptionFirst = m_pVoteOptionFirst; + CVoteOptionServer *pVoteOptionLast = m_pVoteOptionLast; + int NumVoteOptions = m_NumVoteOptions; + CTuningParams Tuning = m_Tuning; + + m_Resetting = true; + this->~CGameContext(); + mem_zero(this, sizeof(*this)); + new (this) CGameContext(RESET); + + m_pVoteOptionHeap = pVoteOptionHeap; + m_pVoteOptionFirst = pVoteOptionFirst; + m_pVoteOptionLast = pVoteOptionLast; + m_NumVoteOptions = NumVoteOptions; + m_Tuning = Tuning; +} + + +class CCharacter *CGameContext::GetPlayerChar(int ClientID) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || !m_apPlayers[ClientID]) + return 0; + return m_apPlayers[ClientID]->GetCharacter(); +} + +void CGameContext::CreateDamage(vec2 Pos, int Id, vec2 Source, int HealthAmount, int ArmorAmount, bool Self) +{ + float f = angle(Source); + CNetEvent_Damage *pEvent = (CNetEvent_Damage *)m_Events.Create(NETEVENTTYPE_DAMAGE, sizeof(CNetEvent_Damage)); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_ClientID = Id; + pEvent->m_Angle = (int)(f*256.0f); + pEvent->m_HealthAmount = HealthAmount; + pEvent->m_ArmorAmount = ArmorAmount; + pEvent->m_Self = Self; + } +} + +void CGameContext::CreateHammerHit(vec2 Pos) +{ + // create the event + CNetEvent_HammerHit *pEvent = (CNetEvent_HammerHit *)m_Events.Create(NETEVENTTYPE_HAMMERHIT, sizeof(CNetEvent_HammerHit)); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + } +} + + +void CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, int MaxDamage) +{ + // create the event + CNetEvent_Explosion *pEvent = (CNetEvent_Explosion *)m_Events.Create(NETEVENTTYPE_EXPLOSION, sizeof(CNetEvent_Explosion)); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + } + + // deal damage + CCharacter *apEnts[MAX_CLIENTS]; + float Radius = g_pData->m_Explosion.m_Radius; + float InnerRadius = 48.0f; + float MaxForce = g_pData->m_Explosion.m_MaxForce; + int Num = m_World.FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; i++) + { + vec2 Diff = apEnts[i]->GetPos() - Pos; + vec2 Force(0, MaxForce); + float l = length(Diff); + if(l) + Force = normalize(Diff) * MaxForce; + float Factor = 1 - clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); + if((int)(Factor * MaxDamage)) + apEnts[i]->TakeDamage(Force * Factor, Diff*-1, (int)(Factor * MaxDamage), Owner, Weapon); + } +} + +void CGameContext::CreatePlayerSpawn(vec2 Pos) +{ + // create the event + CNetEvent_Spawn *ev = (CNetEvent_Spawn *)m_Events.Create(NETEVENTTYPE_SPAWN, sizeof(CNetEvent_Spawn)); + if(ev) + { + ev->m_X = (int)Pos.x; + ev->m_Y = (int)Pos.y; + } +} + +void CGameContext::CreateDeath(vec2 Pos, int ClientID) +{ + // create the event + CNetEvent_Death *pEvent = (CNetEvent_Death *)m_Events.Create(NETEVENTTYPE_DEATH, sizeof(CNetEvent_Death)); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_ClientID = ClientID; + } +} + +void CGameContext::CreateSound(vec2 Pos, int Sound, int64 Mask) +{ + if (Sound < 0) + return; + + // create a sound + CNetEvent_SoundWorld *pEvent = (CNetEvent_SoundWorld *)m_Events.Create(NETEVENTTYPE_SOUNDWORLD, sizeof(CNetEvent_SoundWorld), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_SoundID = Sound; + } +} + +void CGameContext::SendChat(int ChatterClientID, int Mode, int To, const char *pText) +{ + char aBuf[256]; + if(ChatterClientID >= 0 && ChatterClientID < MAX_CLIENTS) + { + if(Mode == CHAT_TEAM) + { + int TeamID = m_apPlayers[ChatterClientID]->GetTeam(); + str_format(aBuf, sizeof(aBuf), "%d:%d:%d:%s: %s", Mode, TeamID, ChatterClientID, Server()->ClientName(ChatterClientID), pText); + } + else + str_format(aBuf, sizeof(aBuf), "%d:%d:%s: %s", Mode, ChatterClientID, Server()->ClientName(ChatterClientID), pText); + } + else + str_format(aBuf, sizeof(aBuf), "*** %s", pText); + + const char *pModeStr; + if(Mode == CHAT_WHISPER) + pModeStr = 0; + else if(Mode == CHAT_TEAM) + pModeStr = "teamchat"; + else + pModeStr = "chat"; + + if(pModeStr) + { + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pModeStr, aBuf); + } + + + CNetMsg_Sv_Chat Msg; + Msg.m_Mode = Mode; + Msg.m_ClientID = ChatterClientID; + Msg.m_pMessage = pText; + Msg.m_TargetID = -1; + + if(Mode == CHAT_ALL) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); + else if(Mode == CHAT_TEAM) + { + // pack one for the recording only + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + + To = m_apPlayers[ChatterClientID]->GetTeam(); + + // send to the clients + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() == To) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + } + else // Mode == CHAT_WHISPER + { + // send to the clients + Msg.m_TargetID = To; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ChatterClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, To); + } +} + +void CGameContext::SendBroadcast(const char* pText, int ClientID) +{ + CNetMsg_Sv_Broadcast Msg; + Msg.m_pMessage = pText; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendEmoticon(int ClientID, int Emoticon) +{ + CNetMsg_Sv_Emoticon Msg; + Msg.m_ClientID = ClientID; + Msg.m_Emoticon = Emoticon; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); +} + +void CGameContext::SendWeaponPickup(int ClientID, int Weapon) +{ + CNetMsg_Sv_WeaponPickup Msg; + Msg.m_Weapon = Weapon; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendMotd(int ClientID) +{ + CNetMsg_Sv_Motd Msg; + Msg.m_pMessage = Config()->m_SvMotd; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendSettings(int ClientID) +{ + CNetMsg_Sv_ServerSettings Msg; + Msg.m_KickVote = Config()->m_SvVoteKick; + Msg.m_KickMin = Config()->m_SvVoteKickMin; + Msg.m_SpecVote = Config()->m_SvVoteSpectate; + Msg.m_TeamLock = m_LockTeams != 0; + Msg.m_TeamBalance = Config()->m_SvTeambalanceTime != 0; + Msg.m_PlayerSlots = Config()->m_SvPlayerSlots; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendSkinChange(int ClientID, int TargetID) +{ + CNetMsg_Sv_SkinChange Msg; + Msg.m_ClientID = ClientID; + for(int p = 0; p < NUM_SKINPARTS; p++) + { + Msg.m_apSkinPartNames[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aaSkinPartNames[p]; + Msg.m_aUseCustomColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aUseCustomColors[p]; + Msg.m_aSkinPartColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aSkinPartColors[p]; + } + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, TargetID); +} + +void CGameContext::SendGameMsg(int GameMsgID, int ClientID) +{ + CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); + Msg.AddInt(GameMsgID); + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ClientID) +{ + CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); + Msg.AddInt(GameMsgID); + Msg.AddInt(ParaI1); + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID) +{ + CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); + Msg.AddInt(GameMsgID); + Msg.AddInt(ParaI1); + Msg.AddInt(ParaI2); + Msg.AddInt(ParaI3); + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendChatCommand(const CCommandManager::CCommand *pCommand, int ClientID) +{ + CNetMsg_Sv_CommandInfo Msg; + Msg.m_Name = pCommand->m_aName; + Msg.m_HelpText = pCommand->m_aHelpText; + Msg.m_ArgsFormat = pCommand->m_aArgsFormat; + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendChatCommands(int ClientID) +{ + for(int i = 0; i < CommandManager()->CommandCount(); i++) + { + SendChatCommand(CommandManager()->GetCommand(i), ClientID); + } +} + +void CGameContext::SendRemoveChatCommand(const CCommandManager::CCommand *pCommand, int ClientID) +{ + CNetMsg_Sv_CommandInfoRemove Msg; + Msg.m_Name = pCommand->m_aName; + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +// +void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char *pReason) +{ + // check if a vote is already running + if(m_VoteCloseTime) + return; + + // reset votes + m_VoteEnforce = VOTE_CHOICE_PASS; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + { + m_apPlayers[i]->m_Vote = VOTE_CHOICE_PASS; + m_apPlayers[i]->m_VotePos = 0; + } + } + + // start vote + m_VoteCloseTime = time_get() + time_freq()*VOTE_TIME; + m_VoteCancelTime = time_get() + time_freq()*VOTE_CANCEL_TIME; + str_copy(m_aVoteDescription, pDesc, sizeof(m_aVoteDescription)); + str_copy(m_aVoteCommand, pCommand, sizeof(m_aVoteCommand)); + str_copy(m_aVoteReason, pReason, sizeof(m_aVoteReason)); + SendVoteSet(m_VoteType, -1); + m_VoteUpdate = true; +} + + +void CGameContext::EndVote(int Type, bool Force) +{ + m_VoteCloseTime = 0; + m_VoteCancelTime = 0; + if(Force) + m_VoteCreator = -1; + SendVoteSet(Type, -1); +} + +void CGameContext::ForceVote(int Type, const char *pDescription, const char *pReason) +{ + CNetMsg_Sv_VoteSet Msg; + Msg.m_Type = Type; + Msg.m_Timeout = 0; + Msg.m_ClientID = -1; + Msg.m_pDescription = pDescription; + Msg.m_pReason = pReason; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); +} + +void CGameContext::SendVoteSet(int Type, int ToClientID) +{ + CNetMsg_Sv_VoteSet Msg; + if(m_VoteCloseTime) + { + Msg.m_ClientID = m_VoteCreator; + Msg.m_Type = Type; + Msg.m_Timeout = (m_VoteCloseTime-time_get())/time_freq(); + Msg.m_pDescription = m_aVoteDescription; + Msg.m_pReason = m_aVoteReason; + } + else + { + Msg.m_Type = Type; + Msg.m_Timeout = 0; + Msg.m_ClientID = m_VoteCreator; + Msg.m_pDescription = ""; + Msg.m_pReason = ""; + } + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ToClientID); +} + +void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) +{ + CNetMsg_Sv_VoteStatus Msg = {0}; + Msg.m_Total = Total; + Msg.m_Yes = Yes; + Msg.m_No = No; + Msg.m_Pass = Total - (Yes+No); + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); + +} + +void CGameContext::AbortVoteOnDisconnect(int ClientID) +{ + if(m_VoteCloseTime && ClientID == m_VoteClientID && (str_startswith(m_aVoteCommand, "kick ") || + str_startswith(m_aVoteCommand, "set_team ") || (str_startswith(m_aVoteCommand, "ban ") && Server()->IsBanned(ClientID)))) + m_VoteCloseTime = -1; +} + +void CGameContext::AbortVoteOnTeamChange(int ClientID) +{ + if(m_VoteCloseTime && ClientID == m_VoteClientID && str_startswith(m_aVoteCommand, "set_team ")) + m_VoteCloseTime = -1; +} + + +void CGameContext::CheckPureTuning() +{ + // might not be created yet during start up + if(!m_pController) + return; + + if( str_comp(m_pController->GetGameType(), "DM")==0 || + str_comp(m_pController->GetGameType(), "TDM")==0 || + str_comp(m_pController->GetGameType(), "CTF")==0 || + str_comp(m_pController->GetGameType(), "LMS")==0 || + str_comp(m_pController->GetGameType(), "LTS")==0) + { + CTuningParams p; + if(mem_comp(&p, &m_Tuning, sizeof(p)) != 0) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "resetting tuning due to pure server"); + m_Tuning = p; + } + } +} + +void CGameContext::SendTuningParams(int ClientID) +{ + CheckPureTuning(); + + CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); + int *pParams = (int *)&m_Tuning; + for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) + Msg.AddInt(pParams[i]); + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SwapTeams() +{ + if(!m_pController->IsTeamplay()) + return; + + SendGameMsg(GAMEMSG_TEAM_SWAP, -1); + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + m_pController->DoTeamChange(m_apPlayers[i], m_apPlayers[i]->GetTeam()^1, false); + } + + m_pController->SwapTeamscore(); +} + +void CGameContext::OnTick() +{ + // check tuning + CheckPureTuning(); + + // copy tuning + m_World.m_Core.m_Tuning = m_Tuning; + m_World.Tick(); + + //if(world.paused) // make sure that the game object always updates + m_pController->Tick(); + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + { + m_apPlayers[i]->Tick(); + m_apPlayers[i]->PostTick(); + } + } + + // update voting + if(m_VoteCloseTime) + { + // abort the kick-vote on player-leave + if(m_VoteCloseTime == -1) + EndVote(VOTE_END_ABORT, false); + else + { + int Total = 0, Yes = 0, No = 0; + if(m_VoteUpdate) + { + // count votes + char aaBuf[MAX_CLIENTS][NETADDR_MAXSTRSIZE] = {{0}}; + for(int i = 0; i < MAX_CLIENTS; i++) + if(m_apPlayers[i]) + Server()->GetClientAddr(i, aaBuf[i], NETADDR_MAXSTRSIZE); + bool aVoteChecked[MAX_CLIENTS] = {0}; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || aVoteChecked[i]) // don't count in votes by spectators + continue; + + int ActVote = m_apPlayers[i]->m_Vote; + int ActVotePos = m_apPlayers[i]->m_VotePos; + + // check for more players with the same ip (only use the vote of the one who voted first) + for(int j = i+1; j < MAX_CLIENTS; ++j) + { + if(!m_apPlayers[j] || aVoteChecked[j] || str_comp(aaBuf[j], aaBuf[i])) + continue; + + aVoteChecked[j] = true; + if(m_apPlayers[j]->m_Vote && (!ActVote || ActVotePos > m_apPlayers[j]->m_VotePos)) + { + ActVote = m_apPlayers[j]->m_Vote; + ActVotePos = m_apPlayers[j]->m_VotePos; + } + } + + Total++; + if(ActVote > 0) + Yes++; + else if(ActVote < 0) + No++; + } + } + + if(m_VoteEnforce == VOTE_CHOICE_YES || (m_VoteUpdate && Yes >= Total/2+1)) + { + Server()->SetRconCID(IServer::RCON_CID_VOTE); + Console()->ExecuteLine(m_aVoteCommand); + Server()->SetRconCID(IServer::RCON_CID_SERV); + if(m_VoteCreator != -1 && m_apPlayers[m_VoteCreator]) + m_apPlayers[m_VoteCreator]->m_LastVoteCallTick = 0; + + EndVote(VOTE_END_PASS, m_VoteEnforce == VOTE_CHOICE_YES); + } + else if(m_VoteEnforce == VOTE_CHOICE_NO || (m_VoteUpdate && No >= (Total+1)/2) || time_get() > m_VoteCloseTime) + EndVote(VOTE_END_FAIL, m_VoteEnforce == VOTE_CHOICE_NO); + else if(m_VoteUpdate) + { + m_VoteUpdate = false; + SendVoteStatus(-1, Total, Yes, No); + } + } + } + + +#ifdef CONF_DEBUG + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i] && m_apPlayers[i]->IsDummy()) + { + CNetObj_PlayerInput Input = {0}; + Input.m_Direction = (i&1)?-1:1; + m_apPlayers[i]->OnPredictedInput(&Input); + } + } +#endif +} + +// Server hooks +void CGameContext::OnClientDirectInput(int ClientID, void *pInput) +{ + int NumFailures = m_NetObjHandler.NumObjFailures(); + if(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == -1) + { + if(Config()->m_Debug && NumFailures != m_NetObjHandler.NumObjFailures()) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "NETOBJTYPE_PLAYERINPUT failed on '%s'", m_NetObjHandler.FailedObjOn()); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + else + m_apPlayers[ClientID]->OnDirectInput((CNetObj_PlayerInput *)pInput); +} + +void CGameContext::OnClientPredictedInput(int ClientID, void *pInput) +{ + if(!m_World.m_Paused) + { + int NumFailures = m_NetObjHandler.NumObjFailures(); + if(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == -1) + { + if(Config()->m_Debug && NumFailures != m_NetObjHandler.NumObjFailures()) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "NETOBJTYPE_PLAYERINPUT corrected on '%s'", m_NetObjHandler.FailedObjOn()); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + else + m_apPlayers[ClientID]->OnPredictedInput((CNetObj_PlayerInput *)pInput); + } +} + +void CGameContext::OnClientEnter(int ClientID) +{ + // send chat commands + SendChatCommands(ClientID); + + m_pController->OnPlayerConnect(m_apPlayers[ClientID]); + + m_VoteUpdate = true; + + // update client infos (others before local) + CNetMsg_Sv_ClientInfo NewClientInfoMsg; + NewClientInfoMsg.m_ClientID = ClientID; + NewClientInfoMsg.m_Local = 0; + NewClientInfoMsg.m_Team = m_apPlayers[ClientID]->GetTeam(); + NewClientInfoMsg.m_pName = Server()->ClientName(ClientID); + NewClientInfoMsg.m_pClan = Server()->ClientClan(ClientID); + NewClientInfoMsg.m_Country = Server()->ClientCountry(ClientID); + NewClientInfoMsg.m_Silent = false; + + if(Config()->m_SvSilentSpectatorMode && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS) + NewClientInfoMsg.m_Silent = true; + + for(int p = 0; p < NUM_SKINPARTS; p++) + { + NewClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aaSkinPartNames[p]; + NewClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aUseCustomColors[p]; + NewClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aSkinPartColors[p]; + } + + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == ClientID || !m_apPlayers[i] || (!Server()->ClientIngame(i) && !m_apPlayers[i]->IsDummy())) + continue; + + // new info for others + if(Server()->ClientIngame(i)) + Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + + // existing infos for new player + CNetMsg_Sv_ClientInfo ClientInfoMsg; + ClientInfoMsg.m_ClientID = i; + ClientInfoMsg.m_Local = 0; + ClientInfoMsg.m_Team = m_apPlayers[i]->GetTeam(); + ClientInfoMsg.m_pName = Server()->ClientName(i); + ClientInfoMsg.m_pClan = Server()->ClientClan(i); + ClientInfoMsg.m_Country = Server()->ClientCountry(i); + ClientInfoMsg.m_Silent = false; + for(int p = 0; p < NUM_SKINPARTS; p++) + { + ClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[i]->m_TeeInfos.m_aaSkinPartNames[p]; + ClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[i]->m_TeeInfos.m_aUseCustomColors[p]; + ClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[i]->m_TeeInfos.m_aSkinPartColors[p]; + } + Server()->SendPackMsg(&ClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + } + + // local info + NewClientInfoMsg.m_Local = 1; + Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + + if(Server()->DemoRecorder_IsRecording()) + { + CNetMsg_De_ClientEnter Msg; + Msg.m_pName = NewClientInfoMsg.m_pName; + Msg.m_ClientID = ClientID; + Msg.m_Team = NewClientInfoMsg.m_Team; + Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1); + } +} + +void CGameContext::OnClientConnected(int ClientID, bool Dummy, bool AsSpec) +{ + dbg_assert(!m_apPlayers[ClientID], "non-free player slot"); + + m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, Dummy, AsSpec); + + if(Dummy) + return; + + // send active vote + if(m_VoteCloseTime) + SendVoteSet(m_VoteType, ClientID); + + // send motd + SendMotd(ClientID); + + // send settings + SendSettings(ClientID); +} + +void CGameContext::OnClientTeamChange(int ClientID) +{ + if(m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS) + AbortVoteOnTeamChange(ClientID); + + // mark client's projectile has team projectile + CProjectile *p = (CProjectile *)m_World.FindFirst(CGameWorld::ENTTYPE_PROJECTILE); + for(; p; p = (CProjectile *)p->TypeNext()) + { + if(p->GetOwner() == ClientID) + p->LoseOwner(); + } +} + +void CGameContext::OnClientDrop(int ClientID, const char *pReason) +{ + AbortVoteOnDisconnect(ClientID); + m_pController->OnPlayerDisconnect(m_apPlayers[ClientID]); + + // update clients on drop + if(Server()->ClientIngame(ClientID) || IsClientBot(ClientID)) + { + if(Server()->DemoRecorder_IsRecording()) + { + CNetMsg_De_ClientLeave Msg; + Msg.m_pName = Server()->ClientName(ClientID); + Msg.m_pReason = pReason; + Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1); + } + + CNetMsg_Sv_ClientDrop Msg; + Msg.m_ClientID = ClientID; + Msg.m_pReason = pReason; + Msg.m_Silent = false; + if(Config()->m_SvSilentSpectatorMode && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS) + Msg.m_Silent = true; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + } + + // mark client's projectile has team projectile + CProjectile *p = (CProjectile *)m_World.FindFirst(CGameWorld::ENTTYPE_PROJECTILE); + for(; p; p = (CProjectile *)p->TypeNext()) + { + if(p->GetOwner() == ClientID) + p->LoseOwner(); + } + + delete m_apPlayers[ClientID]; + m_apPlayers[ClientID] = 0; + + m_VoteUpdate = true; +} + +void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) +{ + void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgID, pUnpacker); + CPlayer *pPlayer = m_apPlayers[ClientID]; + + if(!pRawMsg) + { + if(Config()->m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "dropped weird message '%s' (%d), failed on '%s'", m_NetObjHandler.GetMsgName(MsgID), MsgID, m_NetObjHandler.FailedMsgOn()); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + return; + } + + if(Server()->ClientIngame(ClientID)) + { + if(MsgID == NETMSGTYPE_CL_SAY) + { + if(Config()->m_SvSpamprotection && pPlayer->m_LastChatTeamTick && pPlayer->m_LastChatTeamTick+Server()->TickSpeed() > Server()->Tick()) + return; + + CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg; + + // trim right and set maximum length to 128 utf8-characters + int Length = 0; + const char *p = pMsg->m_pMessage; + const char *pEnd = 0; + while(*p) + { + const char *pStrOld = p; + int Code = str_utf8_decode(&p); + + // check if unicode is not empty + if(!str_utf8_is_whitespace(Code)) + { + pEnd = 0; + } + else if(pEnd == 0) + pEnd = pStrOld; + + if(++Length >= 127) + { + *(const_cast(p)) = 0; + break; + } + } + if(pEnd != 0) + *(const_cast(pEnd)) = 0; + + // drop empty and autocreated spam messages (more than 20 characters per second) + if(Length == 0 || (Config()->m_SvSpamprotection && pPlayer->m_LastChatTeamTick && pPlayer->m_LastChatTeamTick + Server()->TickSpeed()*(Length/20) > Server()->Tick())) + return; + + pPlayer->m_LastChatTeamTick = Server()->Tick(); + + // don't allow spectators to disturb players during a running game in tournament mode + int Mode = pMsg->m_Mode; + if((Config()->m_SvTournamentMode == 2) && + pPlayer->GetTeam() == TEAM_SPECTATORS && + m_pController->IsGameRunning() && + !Server()->IsAuthed(ClientID)) + { + if(Mode != CHAT_WHISPER) + Mode = CHAT_TEAM; + else if(m_apPlayers[pMsg->m_Target] && m_apPlayers[pMsg->m_Target]->GetTeam() != TEAM_SPECTATORS) + Mode = CHAT_NONE; + } + + if(Mode != CHAT_NONE) + SendChat(ClientID, Mode, pMsg->m_Target, pMsg->m_pMessage); + } + else if(MsgID == NETMSGTYPE_CL_CALLVOTE) + { + CNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)pRawMsg; + int64 Now = Server()->Tick(); + + if(pMsg->m_Force) + { + if(!Server()->IsAuthed(ClientID)) + return; + } + else + { + if((Config()->m_SvSpamprotection && ((pPlayer->m_LastVoteTryTick && pPlayer->m_LastVoteTryTick+Server()->TickSpeed()*3 > Now) || + (pPlayer->m_LastVoteCallTick && pPlayer->m_LastVoteCallTick+Server()->TickSpeed()*VOTE_COOLDOWN > Now))) || + pPlayer->GetTeam() == TEAM_SPECTATORS || m_VoteCloseTime) + return; + + pPlayer->m_LastVoteTryTick = Now; + } + + m_VoteType = VOTE_UNKNOWN; + char aDesc[VOTE_DESC_LENGTH] = {0}; + char aCmd[VOTE_CMD_LENGTH] = {0}; + const char *pReason = pMsg->m_Reason[0] ? pMsg->m_Reason : "No reason given"; + + if(str_comp_nocase(pMsg->m_Type, "option") == 0) + { + CVoteOptionServer *pOption = m_pVoteOptionFirst; + while(pOption) + { + if(str_comp_nocase(pMsg->m_Value, pOption->m_aDescription) == 0) + { + str_format(aDesc, sizeof(aDesc), "%s", pOption->m_aDescription); + str_format(aCmd, sizeof(aCmd), "%s", pOption->m_aCommand); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), + "'%d:%s' voted %s '%s' reason='%s' cmd='%s' force=%d", + ClientID, Server()->ClientName(ClientID), pMsg->m_Type, + aDesc, pReason, aCmd, pMsg->m_Force + ); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + if(pMsg->m_Force) + { + Server()->SetRconCID(ClientID); + Console()->ExecuteLine(aCmd); + Server()->SetRconCID(IServer::RCON_CID_SERV); + ForceVote(VOTE_START_OP, aDesc, pReason); + return; + } + m_VoteType = VOTE_START_OP; + break; + } + + pOption = pOption->m_pNext; + } + + if(!pOption) + return; + } + else if(str_comp_nocase(pMsg->m_Type, "kick") == 0) + { + if(!Config()->m_SvVoteKick || m_pController->GetRealPlayerNum() < Config()->m_SvVoteKickMin) + return; + + int KickID = str_toint(pMsg->m_Value); + if(KickID < 0 || KickID >= MAX_CLIENTS || !m_apPlayers[KickID] || KickID == ClientID || Server()->IsAuthed(KickID)) + return; + + str_format(aDesc, sizeof(aDesc), "%2d: %s", KickID, Server()->ClientName(KickID)); + if (!Config()->m_SvVoteKickBantime) + str_format(aCmd, sizeof(aCmd), "kick %d Kicked by vote", KickID); + else + { + char aAddrStr[NETADDR_MAXSTRSIZE] = {0}; + Server()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr)); + str_format(aCmd, sizeof(aCmd), "ban %s %d Banned by vote", aAddrStr, Config()->m_SvVoteKickBantime); + } + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), + "'%d:%s' voted %s '%d:%s' reason='%s' cmd='%s' force=%d", + ClientID, Server()->ClientName(ClientID), pMsg->m_Type, + KickID, Server()->ClientName(KickID), pReason, aCmd, pMsg->m_Force + ); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + if(pMsg->m_Force) + { + Server()->SetRconCID(ClientID); + Console()->ExecuteLine(aCmd); + Server()->SetRconCID(IServer::RCON_CID_SERV); + return; + } + m_VoteType = VOTE_START_KICK; + m_VoteClientID = KickID; + } + else if(str_comp_nocase(pMsg->m_Type, "spectate") == 0) + { + if(!Config()->m_SvVoteSpectate) + return; + + int SpectateID = str_toint(pMsg->m_Value); + if(SpectateID < 0 || SpectateID >= MAX_CLIENTS || !m_apPlayers[SpectateID] || m_apPlayers[SpectateID]->GetTeam() == TEAM_SPECTATORS || SpectateID == ClientID) + return; + + str_format(aDesc, sizeof(aDesc), "%2d: %s", SpectateID, Server()->ClientName(SpectateID)); + str_format(aCmd, sizeof(aCmd), "set_team %d -1 %d", SpectateID, Config()->m_SvVoteSpectateRejoindelay); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), + "'%d:%s' voted %s '%d:%s' reason='%s' cmd='%s' force=%d", + ClientID, Server()->ClientName(ClientID), pMsg->m_Type, + SpectateID, Server()->ClientName(SpectateID), pReason, aCmd, pMsg->m_Force + ); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + if(pMsg->m_Force) + { + Server()->SetRconCID(ClientID); + Console()->ExecuteLine(aCmd); + Server()->SetRconCID(IServer::RCON_CID_SERV); + ForceVote(VOTE_START_SPEC, aDesc, pReason); + return; + } + m_VoteType = VOTE_START_SPEC; + m_VoteClientID = SpectateID; + } + + if(m_VoteType != VOTE_UNKNOWN) + { + m_VoteCreator = ClientID; + StartVote(aDesc, aCmd, pReason); + pPlayer->m_Vote = VOTE_CHOICE_YES; + pPlayer->m_VotePos = m_VotePos = 1; + pPlayer->m_LastVoteCallTick = Now; + } + } + else if(MsgID == NETMSGTYPE_CL_VOTE) + { + if(!m_VoteCloseTime) + return; + + if(pPlayer->m_Vote == VOTE_CHOICE_PASS) + { + CNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)pRawMsg; + if(pMsg->m_Vote == VOTE_CHOICE_PASS) + return; + + pPlayer->m_Vote = pMsg->m_Vote; + pPlayer->m_VotePos = ++m_VotePos; + m_VoteUpdate = true; + } + else if(m_VoteCreator == pPlayer->GetCID()) + { + CNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)pRawMsg; + if(pMsg->m_Vote != VOTE_CHOICE_NO || m_VoteCancelTimeIsTeamChangeAllowed()) + { + CNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)pRawMsg; + + if(pPlayer->GetTeam() == pMsg->m_Team || + (Config()->m_SvSpamprotection && pPlayer->m_LastSetTeamTick && pPlayer->m_LastSetTeamTick+Server()->TickSpeed()*3 > Server()->Tick()) || + (pMsg->m_Team != TEAM_SPECTATORS && m_LockTeams) || pPlayer->m_TeamChangeTick > Server()->Tick()) + return; + + pPlayer->m_LastSetTeamTick = Server()->Tick(); + + // Switch team on given client and kill/respawn him + if(m_pController->CanJoinTeam(pMsg->m_Team, ClientID) && m_pController->CanChangeTeam(pPlayer, pMsg->m_Team)) + { + if(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS) + m_VoteUpdate = true; + pPlayer->m_TeamChangeTick = Server()->Tick()+Server()->TickSpeed()*3; + m_pController->DoTeamChange(pPlayer, pMsg->m_Team); + } + } + else if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) + { + CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg; + + if(Config()->m_SvSpamprotection && pPlayer->m_LastSetSpectatorModeTick && pPlayer->m_LastSetSpectatorModeTick+Server()->TickSpeed() > Server()->Tick()) + return; + + pPlayer->m_LastSetSpectatorModeTick = Server()->Tick(); + if(!pPlayer->SetSpectatorID(pMsg->m_SpecMode, pMsg->m_SpectatorID)) + SendGameMsg(GAMEMSG_SPEC_INVALIDID, ClientID); + } + else if (MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused) + { + CNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)pRawMsg; + + if(Config()->m_SvSpamprotection && pPlayer->m_LastEmoteTick && pPlayer->m_LastEmoteTick+Server()->TickSpeed()*3 > Server()->Tick()) + return; + + pPlayer->m_LastEmoteTick = Server()->Tick(); + + SendEmoticon(ClientID, pMsg->m_Emoticon); + } + else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) + { + if(pPlayer->m_LastKillTick && pPlayer->m_LastKillTick+Server()->TickSpeed()*3 > Server()->Tick()) + return; + + pPlayer->m_LastKillTick = Server()->Tick(); + pPlayer->KillCharacter(WEAPON_SELF); + } + else if (MsgID == NETMSGTYPE_CL_READYCHANGE) + { + if(pPlayer->m_LastReadyChangeTick && pPlayer->m_LastReadyChangeTick+Server()->TickSpeed()*1 > Server()->Tick()) + return; + + pPlayer->m_LastReadyChangeTick = Server()->Tick(); + m_pController->OnPlayerReadyChange(pPlayer); + } + else if(MsgID == NETMSGTYPE_CL_SKINCHANGE) + { + if(pPlayer->m_LastChangeInfoTick && pPlayer->m_LastChangeInfoTick+Server()->TickSpeed()*5 > Server()->Tick()) + return; + + pPlayer->m_LastChangeInfoTick = Server()->Tick(); + CNetMsg_Cl_SkinChange *pMsg = (CNetMsg_Cl_SkinChange *)pRawMsg; + + for(int p = 0; p < NUM_SKINPARTS; p++) + { + str_utf8_copy_num(pPlayer->m_TeeInfos.m_aaSkinPartNames[p], pMsg->m_apSkinPartNames[p], sizeof(pPlayer->m_TeeInfos.m_aaSkinPartNames[p]), MAX_SKIN_LENGTH); + pPlayer->m_TeeInfos.m_aUseCustomColors[p] = pMsg->m_aUseCustomColors[p]; + pPlayer->m_TeeInfos.m_aSkinPartColors[p] = pMsg->m_aSkinPartColors[p]; + } + + // update all clients + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(!m_apPlayers[i] || (!Server()->ClientIngame(i) && !m_apPlayers[i]->IsDummy()) || Server()->GetClientVersion(i) < MIN_SKINCHANGE_CLIENTVERSION) + continue; + + SendSkinChange(pPlayer->GetCID(), i); + } + + m_pController->OnPlayerInfoChange(pPlayer); + } + else if (MsgID == NETMSGTYPE_CL_COMMAND) + { + CNetMsg_Cl_Command *pMsg = (CNetMsg_Cl_Command*)pRawMsg; + CommandManager()->OnCommand(pMsg->m_Name, pMsg->m_Arguments, ClientID); + } + } + else + { + if (MsgID == NETMSGTYPE_CL_STARTINFO) + { + if(pPlayer->m_IsReadyToEnter) + return; + + CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg; + pPlayer->m_LastChangeInfoTick = Server()->Tick(); + + // set start infos + Server()->SetClientName(ClientID, pMsg->m_pName); + Server()->SetClientClan(ClientID, pMsg->m_pClan); + Server()->SetClientCountry(ClientID, pMsg->m_Country); + + for(int p = 0; p < NUM_SKINPARTS; p++) + { + str_utf8_copy_num(pPlayer->m_TeeInfos.m_aaSkinPartNames[p], pMsg->m_apSkinPartNames[p], sizeof(pPlayer->m_TeeInfos.m_aaSkinPartNames[p]), MAX_SKIN_LENGTH); + pPlayer->m_TeeInfos.m_aUseCustomColors[p] = pMsg->m_aUseCustomColors[p]; + pPlayer->m_TeeInfos.m_aSkinPartColors[p] = pMsg->m_aSkinPartColors[p]; + } + + m_pController->OnPlayerInfoChange(pPlayer); + + // send vote options + CNetMsg_Sv_VoteClearOptions ClearMsg; + Server()->SendPackMsg(&ClearMsg, MSGFLAG_VITAL, ClientID); + + CVoteOptionServer *pCurrent = m_pVoteOptionFirst; + while(pCurrent) + { + // count options for actual packet + int NumOptions = 0; + for(CVoteOptionServer *p = pCurrent; p && NumOptions < MAX_VOTE_OPTION_ADD; p = p->m_pNext, ++NumOptions); + + // pack and send vote list packet + CMsgPacker Msg(NETMSGTYPE_SV_VOTEOPTIONLISTADD); + Msg.AddInt(NumOptions); + while(pCurrent && NumOptions--) + { + Msg.AddString(pCurrent->m_aDescription, VOTE_DESC_LENGTH); + pCurrent = pCurrent->m_pNext; + } + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); + } + + // send tuning parameters to client + SendTuningParams(ClientID); + + // client is ready to enter + pPlayer->m_IsReadyToEnter = true; + CNetMsg_Sv_ReadyToEnter m; + Server()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + } + } +} + +void CGameContext::ConTuneParam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pParamName = pResult->GetString(0); + + char aBuf[256]; + if(pResult->NumArguments() == 2) + { + float NewValue = pResult->GetFloat(1); + if(pSelf->Tuning()->Set(pParamName, NewValue) && pSelf->Tuning()->Get(pParamName, &NewValue)) + { + str_format(aBuf, sizeof(aBuf), "%s changed to %.2f", pParamName, NewValue); + pSelf->SendTuningParams(-1); + } + else + { + str_format(aBuf, sizeof(aBuf), "No such tuning parameter: %s", pParamName); + } + } + else + { + float Value; + if(pSelf->Tuning()->Get(pParamName, &Value)) + { + str_format(aBuf, sizeof(aBuf), "%s %.2f", pParamName, Value); + } + else + { + str_format(aBuf, sizeof(aBuf), "No such tuning parameter: %s", pParamName); + } + } + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); +} + +void CGameContext::ConTuneReset(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + CTuningParams TuningParams; + + if(pResult->NumArguments()) + { + const char *pParamName = pResult->GetString(0); + float DefaultValue = 0.0f; + char aBuf[256]; + if(TuningParams.Get(pParamName, &DefaultValue) && pSelf->Tuning()->Set(pParamName, DefaultValue)) + { + str_format(aBuf, sizeof(aBuf), "%s reset to %.2f", pParamName, DefaultValue); + pSelf->SendTuningParams(-1); + } + else + { + str_format(aBuf, sizeof(aBuf), "No such tuning parameter: %s", pParamName); + } + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + } + else + { + *pSelf->Tuning() = TuningParams; + pSelf->SendTuningParams(-1); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "Tuning reset"); + } +} + +void CGameContext::ConTunes(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + char aBuf[256]; + for(int i = 0; i < pSelf->Tuning()->Num(); i++) + { + float Value; + pSelf->Tuning()->Get(i, &Value); + str_format(aBuf, sizeof(aBuf), "%s %.2f", pSelf->Tuning()->GetName(i), Value); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + } +} + +void CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + if(pResult->NumArguments()) + pSelf->m_pController->DoPause(clamp(pResult->GetInteger(0), -1, 1000)); + else + pSelf->m_pController->DoPause(pSelf->m_pController->IsGamePaused() ? 0 : IGameController::TIMER_INFINITE); +} + +void CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->m_pController->ChangeMap(pResult->NumArguments() ? pResult->GetString(0) : ""); +} + +void CGameContext::ConRestart(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int Seconds = pResult->NumArguments() ? clamp(pResult->GetInteger(0), -1, 1000) : 0; + if(Seconds < 0) + pSelf->m_pController->AbortWarmup(); + else + pSelf->m_pController->DoWarmup(Seconds); +} + +void CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SendChat(-1, CHAT_ALL, -1, pResult->GetString(0)); +} + +void CGameContext::ConBroadcast(IConsole::IResult* pResult, void* pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SendBroadcast(pResult->GetString(0), -1); +} + +void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1); + int Team = clamp(pResult->GetInteger(1), -1, 1); + int Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0; + if(!pSelf->m_apPlayers[ClientID] || !pSelf->m_pController->CanJoinTeam(Team, ClientID)) + return; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "moved client %d to team %d", ClientID, Team); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60; + pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[ClientID], Team); +} + +void CGameContext::ConSetTeamAll(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int Team = clamp(pResult->GetInteger(0), -1, 1); + + pSelf->SendGameMsg(GAMEMSG_TEAM_ALL, Team, -1); + + for(int i = 0; i < MAX_CLIENTS; ++i) + if(pSelf->m_apPlayers[i] && pSelf->m_pController->CanJoinTeam(Team, i)) + pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[i], Team, false); +} + +void CGameContext::ConSwapTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SwapTeams(); +} + +void CGameContext::ConShuffleTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if(!pSelf->m_pController->IsTeamplay()) + return; + + int rnd = 0; + int PlayerTeam = 0; + int aPlayer[MAX_CLIENTS]; + + for(int i = 0; i < MAX_CLIENTS; i++) + if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + aPlayer[PlayerTeam++]=i; + + pSelf->SendGameMsg(GAMEMSG_TEAM_SHUFFLE, -1); + + //creating random permutation + for(int i = PlayerTeam; i > 1; i--) + { + rnd = random_int() % i; + int tmp = aPlayer[rnd]; + aPlayer[rnd] = aPlayer[i-1]; + aPlayer[i-1] = tmp; + } + //uneven Number of Players? + rnd = PlayerTeam % 2 ? random_int() % 2 : 0; + + for(int i = 0; i < PlayerTeam; i++) + pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[aPlayer[i]], i < (PlayerTeam+rnd)/2 ? TEAM_RED : TEAM_BLUE, false); +} + +void CGameContext::ConLockTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->m_LockTeams ^= 1; + pSelf->SendSettings(-1); +} + +void CGameContext::ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->m_pController->ForceTeamBalance(); +} + +void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pDescription = pResult->GetString(0); + const char *pCommand = pResult->GetString(1); + + if(pSelf->m_NumVoteOptions == MAX_VOTE_OPTIONS) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "maximum number of vote options reached"); + return; + } + + // check for valid option + if(!pSelf->Console()->LineIsValid(pCommand) || str_length(pCommand) >= VOTE_CMD_LENGTH) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "skipped invalid command '%s'", pCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + + pDescription = str_skip_whitespaces_const(pDescription); + if(str_length(pDescription) >= VOTE_DESC_LENGTH || *pDescription == 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "skipped invalid option '%s'", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + + // check for duplicate entry + for(CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; pOption; pOption = pOption->m_pNext) + { + if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "option '%s' already exists", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + } + + // add the option + ++pSelf->m_NumVoteOptions; + int Len = str_length(pCommand); + + CVoteOptionServer *pOption = (CVoteOptionServer *)pSelf->m_pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); + pOption->m_pNext = 0; + pOption->m_pPrev = pSelf->m_pVoteOptionLast; + if(pOption->m_pPrev) + pOption->m_pPrev->m_pNext = pOption; + pSelf->m_pVoteOptionLast = pOption; + if(!pSelf->m_pVoteOptionFirst) + pSelf->m_pVoteOptionFirst = pOption; + + str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); + mem_copy(pOption->m_aCommand, pCommand, Len+1); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "added option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + // inform clients about added option + CNetMsg_Sv_VoteOptionAdd OptionMsg; + OptionMsg.m_pDescription = pOption->m_aDescription; + pSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1); +} + +void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pDescription = pResult->GetString(0); + + // check for valid option + CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; + while(pOption) + { + if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) + break; + pOption = pOption->m_pNext; + } + if(!pOption) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "option '%s' does not exist", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + + // inform clients about removed option + CNetMsg_Sv_VoteOptionRemove OptionMsg; + OptionMsg.m_pDescription = pOption->m_aDescription; + pSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1); + + // TODO: improve this + // remove the option + --pSelf->m_NumVoteOptions; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "removed option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + CHeap *pVoteOptionHeap = new CHeap(); + CVoteOptionServer *pVoteOptionFirst = 0; + CVoteOptionServer *pVoteOptionLast = 0; + int NumVoteOptions = pSelf->m_NumVoteOptions; + for(CVoteOptionServer *pSrc = pSelf->m_pVoteOptionFirst; pSrc; pSrc = pSrc->m_pNext) + { + if(pSrc == pOption) + continue; + + // copy option + int Len = str_length(pSrc->m_aCommand); + CVoteOptionServer *pDst = (CVoteOptionServer *)pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); + pDst->m_pNext = 0; + pDst->m_pPrev = pVoteOptionLast; + if(pDst->m_pPrev) + pDst->m_pPrev->m_pNext = pDst; + pVoteOptionLast = pDst; + if(!pVoteOptionFirst) + pVoteOptionFirst = pDst; + + str_copy(pDst->m_aDescription, pSrc->m_aDescription, sizeof(pDst->m_aDescription)); + mem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len+1); + } + + // clean up + delete pSelf->m_pVoteOptionHeap; + pSelf->m_pVoteOptionHeap = pVoteOptionHeap; + pSelf->m_pVoteOptionFirst = pVoteOptionFirst; + pSelf->m_pVoteOptionLast = pVoteOptionLast; + pSelf->m_NumVoteOptions = NumVoteOptions; +} + +void CGameContext::ConClearVotes(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "cleared votes"); + CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg; + pSelf->Server()->SendPackMsg(&VoteClearOptionsMsg, MSGFLAG_VITAL, -1); + pSelf->m_pVoteOptionHeap->Reset(); + pSelf->m_pVoteOptionFirst = 0; + pSelf->m_pVoteOptionLast = 0; + pSelf->m_NumVoteOptions = 0; +} + +void CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + // check if there is a vote running + if(!pSelf->m_VoteCloseTime) + return; + + if(str_comp_nocase(pResult->GetString(0), "yes") == 0) + pSelf->m_VoteEnforce = VOTE_CHOICE_YES; + else if(str_comp_nocase(pResult->GetString(0), "no") == 0) + pSelf->m_VoteEnforce = VOTE_CHOICE_NO; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "forcing vote %s", pResult->GetString(0)); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); +} + +void CGameContext::ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + { + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SendMotd(-1); + } +} + +void CGameContext::ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + { + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SendSettings(-1); + } +} + +void CGameContext::ConchainGameinfoUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + { + CGameContext *pSelf = (CGameContext *)pUserData; + if(pSelf->m_pController) + pSelf->m_pController->CheckGameInfo(); + } +} + +void CGameContext::OnConsoleInit() +{ + m_pServer = Kernel()->RequestInterface(); + m_pConfig = Kernel()->RequestInterface()->Values(); + m_pConsole = Kernel()->RequestInterface(); + + Console()->Register("tune", "s[tuning] ?i[value]", CFGFLAG_SERVER, ConTuneParam, this, "Tune variable to value or show current value"); + Console()->Register("tune_reset", "?s[tuning]", CFGFLAG_SERVER, ConTuneReset, this, "Reset all or one tuning variable to default"); + Console()->Register("tunes", "", CFGFLAG_SERVER, ConTunes, this, "List all tuning variables and their values"); + + Console()->Register("pause", "?i[seconds]", CFGFLAG_SERVER|CFGFLAG_STORE, ConPause, this, "Pause/unpause game"); + Console()->Register("change_map", "?r[map]", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, "Change map"); + Console()->Register("restart", "?i[seconds]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (-1 = abort)"); + Console()->Register("say", "r[text]", CFGFLAG_SERVER, ConSay, this, "Say in chat"); + Console()->Register("broadcast", "r[text]", CFGFLAG_SERVER, ConBroadcast, this, "Broadcast message"); + Console()->Register("set_team", "i[id] i[team] ?i[delay]", CFGFLAG_SERVER, ConSetTeam, this, "Set team of player to team"); + Console()->Register("set_team_all", "i[team]", CFGFLAG_SERVER, ConSetTeamAll, this, "Set team of all players to team"); + Console()->Register("swap_teams", "", CFGFLAG_SERVER, ConSwapTeams, this, "Swap the current teams"); + Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, ConShuffleTeams, this, "Shuffle the current teams"); + Console()->Register("lock_teams", "", CFGFLAG_SERVER, ConLockTeams, this, "Lock/unlock teams"); + Console()->Register("force_teambalance", "", CFGFLAG_SERVER, ConForceTeamBalance, this, "Force team balance"); + + Console()->Register("add_vote", "s[option] r[command]", CFGFLAG_SERVER, ConAddVote, this, "Add a voting option"); + Console()->Register("remove_vote", "s[option]", CFGFLAG_SERVER, ConRemoveVote, this, "remove a voting option"); + Console()->Register("clear_votes", "", CFGFLAG_SERVER, ConClearVotes, this, "Clears the voting options"); + Console()->Register("vote", "r['yes'|'no']", CFGFLAG_SERVER, ConVote, this, "Force a vote to yes/no"); +} + +void CGameContext::NewCommandHook(const CCommandManager::CCommand *pCommand, void *pContext) +{ + CGameContext *pSelf = (CGameContext *)pContext; + pSelf->SendChatCommand(pCommand, -1); +} + +void CGameContext::RemoveCommandHook(const CCommandManager::CCommand *pCommand, void *pContext) +{ + CGameContext *pSelf = (CGameContext *)pContext; + pSelf->SendRemoveChatCommand(pCommand, -1); +} + +void CGameContext::OnInit() +{ + // init everything + m_pServer = Kernel()->RequestInterface(); + m_pConfig = Kernel()->RequestInterface()->Values(); + m_pConsole = Kernel()->RequestInterface(); + m_pStorage = Kernel()->RequestInterface(); + m_World.SetGameServer(this); + m_Events.SetGameServer(this); + m_CommandManager.Init(m_pConsole, this, NewCommandHook, RemoveCommandHook); + + // HACK: only set static size for items, which were available in the first 0.7 release + // so new items don't break the snapshot delta + static const int OLD_NUM_NETOBJTYPES = 23; + for(int i = 0; i < OLD_NUM_NETOBJTYPES; i++) + Server()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); + + m_Layers.Init(Kernel()); + m_Collision.Init(&m_Layers); + + // select gametype + if(str_comp_nocase(Config()->m_SvGametype, "mod") == 0) + m_pController = new CGameControllerMOD(this); + else if(str_comp_nocase(Config()->m_SvGametype, "ctf") == 0) + m_pController = new CGameControllerCTF(this); + else if(str_comp_nocase(Config()->m_SvGametype, "lms") == 0) + m_pController = new CGameControllerLMS(this); + else if(str_comp_nocase(Config()->m_SvGametype, "lts") == 0) + m_pController = new CGameControllerLTS(this); + else if(str_comp_nocase(Config()->m_SvGametype, "tdm") == 0) + m_pController = new CGameControllerTDM(this); + else + m_pController = new CGameControllerDM(this); + + m_pController->RegisterChatCommands(CommandManager()); + + // create all entities from the game layer + CMapItemLayerTilemap *pTileMap = m_Layers.GameLayer(); + CTile *pTiles = (CTile *)Kernel()->RequestInterface()->GetData(pTileMap->m_Data); + for(int y = 0; y < pTileMap->m_Height; y++) + { + for(int x = 0; x < pTileMap->m_Width; x++) + { + int Index = pTiles[y*pTileMap->m_Width+x].m_Index; + + if(Index >= ENTITY_OFFSET) + { + vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); + m_pController->OnEntity(Index-ENTITY_OFFSET, Pos); + } + } + } + + Console()->Chain("sv_motd", ConchainSpecialMotdupdate, this); + + Console()->Chain("sv_vote_kick", ConchainSettingUpdate, this); + Console()->Chain("sv_vote_kick_min", ConchainSettingUpdate, this); + Console()->Chain("sv_vote_spectate", ConchainSettingUpdate, this); + Console()->Chain("sv_teambalance_time", ConchainSettingUpdate, this); + Console()->Chain("sv_player_slots", ConchainSettingUpdate, this); + Console()->Chain("sv_max_clients", ConchainSettingUpdate, this); + + Console()->Chain("sv_scorelimit", ConchainGameinfoUpdate, this); + Console()->Chain("sv_timelimit", ConchainGameinfoUpdate, this); + Console()->Chain("sv_matches_per_map", ConchainGameinfoUpdate, this); + + // clamp sv_player_slots to 0..MaxClients + if(Config()->m_SvMaxClients < Config()->m_SvPlayerSlots) + Config()->m_SvPlayerSlots = Config()->m_SvMaxClients; + +#ifdef CONF_DEBUG + // clamp dbg_dummies to 0..MAX_CLIENTS-1 + if(MAX_CLIENTS <= Config()->m_DbgDummies) + Config()->m_DbgDummies = MAX_CLIENTS; + if(Config()->m_DbgDummies) + { + for(int i = 0; i < Config()->m_DbgDummies ; i++) + OnClientConnected(MAX_CLIENTS -i-1, true, false); + } +#endif +} + +void CGameContext::OnShutdown() +{ + delete m_pController; + m_pController = 0; + Clear(); +} + +void CGameContext::OnSnap(int ClientID) +{ + // add tuning to demo + CTuningParams StandardTuning; + if(ClientID == -1 && Server()->DemoRecorder_IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0) + { + CNetObj_De_TuneParams *pTuneParams = static_cast(Server()->SnapNewItem(NETOBJTYPE_DE_TUNEPARAMS, 0, sizeof(CNetObj_De_TuneParams))); + if(!pTuneParams) + return; + + mem_copy(pTuneParams->m_aTuneParams, &m_Tuning, sizeof(pTuneParams->m_aTuneParams)); + } + + m_World.Snap(ClientID); + m_pController->Snap(ClientID); + m_Events.Snap(ClientID); + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + m_apPlayers[i]->Snap(ClientID); + } +} +void CGameContext::OnPreSnap() {} +void CGameContext::OnPostSnap() +{ + m_World.PostSnap(); + m_Events.Clear(); +} + +bool CGameContext::IsClientBot(int ClientID) const +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->IsDummy(); +} + +bool CGameContext::IsClientReady(int ClientID) const +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_IsReadyToEnter; +} + +bool CGameContext::IsClientPlayer(int ClientID) const +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetTeam() != TEAM_SPECTATORS; +} + +bool CGameContext::IsClientSpectator(int ClientID) const +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS; +} + +const char *CGameContext::GameType() const { return m_pController && m_pController->GetGameType() ? m_pController->GetGameType() : ""; } +const char *CGameContext::Version() const { return GAME_VERSION; } +const char *CGameContext::NetVersion() const { return GAME_NETVERSION; } +const char *CGameContext::NetVersionHashUsed() const { return GAME_NETVERSION_HASH_FORCED; } +const char *CGameContext::NetVersionHashReal() const { return GAME_NETVERSION_HASH; } + +IGameServer *CreateGameServer() { return new CGameContext; } diff --git a/src/game/server/gamecontext.h b/src/game/server/gamecontext.h new file mode 100644 index 000000000..07cf6f816 --- /dev/null +++ b/src/game/server/gamecontext.h @@ -0,0 +1,205 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMECONTEXT_H +#define GAME_SERVER_GAMECONTEXT_H + +#include +#include + +#include +#include +#include + +#include "eventhandler.h" +#include "gameworld.h" + +/* + Tick + Game Context (CGameContext::tick) + Game World (GAMEWORLD::tick) + Reset world if requested (GAMEWORLD::reset) + All entities in the world (ENTITY::tick) + All entities in the world (ENTITY::tick_defered) + Remove entities marked for deletion (GAMEWORLD::remove_entities) + Game Controller (GAMECONTROLLER::tick) + All players (CPlayer::tick) + + + Snap + Game Context (CGameContext::snap) + Game World (GAMEWORLD::snap) + All entities in the world (ENTITY::snap) + Game Controller (GAMECONTROLLER::snap) + Events handler (EVENT_HANDLER::snap) + All players (CPlayer::snap) + +*/ +class CGameContext : public IGameServer +{ + IServer *m_pServer; + class CConfig *m_pConfig; + class IConsole *m_pConsole; + class IStorage *m_pStorage; + CLayers m_Layers; + CCollision m_Collision; + CNetObjHandler m_NetObjHandler; + CTuningParams m_Tuning; + + static void ConTuneParam(IConsole::IResult *pResult, void *pUserData); + static void ConTuneReset(IConsole::IResult *pResult, void *pUserData); + static void ConTunes(IConsole::IResult *pResult, void *pUserData); + static void ConPause(IConsole::IResult *pResult, void *pUserData); + static void ConChangeMap(IConsole::IResult *pResult, void *pUserData); + static void ConRestart(IConsole::IResult *pResult, void *pUserData); + static void ConSay(IConsole::IResult *pResult, void *pUserData); + static void ConBroadcast(IConsole::IResult *pResult, void *pUserData); + static void ConSetTeam(IConsole::IResult *pResult, void *pUserData); + static void ConSetTeamAll(IConsole::IResult *pResult, void *pUserData); + static void ConSwapTeams(IConsole::IResult *pResult, void *pUserData); + static void ConShuffleTeams(IConsole::IResult *pResult, void *pUserData); + static void ConLockTeams(IConsole::IResult *pResult, void *pUserData); + static void ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData); + static void ConAddVote(IConsole::IResult *pResult, void *pUserData); + static void ConRemoveVote(IConsole::IResult *pResult, void *pUserData); + static void ConClearVotes(IConsole::IResult *pResult, void *pUserData); + static void ConVote(IConsole::IResult *pResult, void *pUserData); + static void ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainGameinfoUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + + static void NewCommandHook(const CCommandManager::CCommand *pCommand, void *pContext); + static void RemoveCommandHook(const CCommandManager::CCommand *pCommand, void *pContext); + + CGameContext(int Resetting); + void Construct(int Resetting); + + bool m_Resetting; +public: + IServer *Server() const { return m_pServer; } + class CConfig *Config() { return m_pConfig; } + class IConsole *Console() { return m_pConsole; } + class IStorage *Storage() { return m_pStorage; } + CCollision *Collision() { return &m_Collision; } + CTuningParams *Tuning() { return &m_Tuning; } + + CGameContext(); + ~CGameContext(); + + void Clear(); + + CEventHandler m_Events; + class CPlayer *m_apPlayers[MAX_CLIENTS]; + + class IGameController *m_pController; + CGameWorld m_World; + CCommandManager m_CommandManager; + + CCommandManager *CommandManager() { return &m_CommandManager; } + + // helper functions + class CCharacter *GetPlayerChar(int ClientID); + + int m_LockTeams; + + // voting + void StartVote(const char *pDesc, const char *pCommand, const char *pReason); + void EndVote(int Type, bool Force); + void ForceVote(int Type, const char *pDescription, const char *pReason); + void SendVoteSet(int Type, int ToClientID); + void SendVoteStatus(int ClientID, int Total, int Yes, int No); + void AbortVoteOnDisconnect(int ClientID); + void AbortVoteOnTeamChange(int ClientID); + + int m_VoteCreator; + int m_VoteType; + int64 m_VoteCloseTime; + int64 m_VoteCancelTime; + bool m_VoteUpdate; + int m_VotePos; + char m_aVoteDescription[VOTE_DESC_LENGTH]; + char m_aVoteCommand[VOTE_CMD_LENGTH]; + char m_aVoteReason[VOTE_REASON_LENGTH]; + int m_VoteClientID; + int m_NumVoteOptions; + int m_VoteEnforce; + enum + { + VOTE_TIME=25, + VOTE_CANCEL_TIME = 10, + + MIN_SKINCHANGE_CLIENTVERSION = 0x0703, + MIN_RACE_CLIENTVERSION = 0x0704, + }; + class CHeap *m_pVoteOptionHeap; + CVoteOptionServer *m_pVoteOptionFirst; + CVoteOptionServer *m_pVoteOptionLast; + + // helper functions + void CreateDamage(vec2 Pos, int Id, vec2 Source, int HealthAmount, int ArmorAmount, bool Self); + void CreateExplosion(vec2 Pos, int Owner, int Weapon, int MaxDamage); + void CreateHammerHit(vec2 Pos); + void CreatePlayerSpawn(vec2 Pos); + void CreateDeath(vec2 Pos, int Who); + void CreateSound(vec2 Pos, int Sound, int64 Mask=-1); + + // network + void SendChat(int ChatterClientID, int Mode, int To, const char *pText); + void SendBroadcast(const char *pText, int ClientID); + void SendEmoticon(int ClientID, int Emoticon); + void SendWeaponPickup(int ClientID, int Weapon); + void SendMotd(int ClientID); + void SendSettings(int ClientID); + void SendSkinChange(int ClientID, int TargetID); + + void SendGameMsg(int GameMsgID, int ClientID); + void SendGameMsg(int GameMsgID, int ParaI1, int ClientID); + void SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID); + + void SendChatCommand(const CCommandManager::CCommand *pCommand, int ClientID); + void SendChatCommands(int ClientID); + void SendRemoveChatCommand(const CCommandManager::CCommand *pCommand, int ClientID); + + // + void CheckPureTuning(); + void SendTuningParams(int ClientID); + + // + void SwapTeams(); + + // engine events + virtual void OnInit(); + virtual void OnConsoleInit(); + virtual void OnShutdown(); + + virtual void OnTick(); + virtual void OnPreSnap(); + virtual void OnSnap(int ClientID); + virtual void OnPostSnap(); + + virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID); + + virtual void OnClientConnected(int ClientID, bool AsSpec) { OnClientConnected(ClientID, false, AsSpec); } + void OnClientConnected(int ClientID, bool Dummy, bool AsSpec); + void OnClientTeamChange(int ClientID); + virtual void OnClientEnter(int ClientID); + virtual void OnClientDrop(int ClientID, const char *pReason); + virtual void OnClientDirectInput(int ClientID, void *pInput); + virtual void OnClientPredictedInput(int ClientID, void *pInput); + + virtual bool IsClientBot(int ClientID) const; + virtual bool IsClientReady(int ClientID) const; + virtual bool IsClientPlayer(int ClientID) const; + virtual bool IsClientSpectator(int ClientID) const; + + virtual const char *GameType() const; + virtual const char *Version() const; + virtual const char *NetVersion() const; + virtual const char *NetVersionHashUsed() const; + virtual const char *NetVersionHashReal() const; +}; + +inline int64 CmaskAll() { return -1; } +inline int64 CmaskOne(int ClientID) { return (int64)1< + +#include + +#include "entities/character.h" +#include "entities/pickup.h" +#include "gamecontext.h" +#include "gamecontroller.h" +#include "player.h" + + +IGameController::IGameController(CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; + m_pConfig = m_pGameServer->Config(); + m_pServer = m_pGameServer->Server(); + + // balancing + m_aTeamSize[TEAM_RED] = 0; + m_aTeamSize[TEAM_BLUE] = 0; + m_UnbalancedTick = TBALANCE_OK; + + // game + m_GameState = IGS_GAME_RUNNING; + m_GameStateTimer = TIMER_INFINITE; + m_GameStartTick = Server()->Tick(); + m_MatchCount = 0; + m_RoundCount = 0; + m_SuddenDeath = 0; + m_aTeamscore[TEAM_RED] = 0; + m_aTeamscore[TEAM_BLUE] = 0; + if(Config()->m_SvWarmup) + SetGameState(IGS_WARMUP_USER, Config()->m_SvWarmup); + else + SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); + + // info + m_GameFlags = 0; + m_pGameType = "unknown"; + m_GameInfo.m_MatchCurrent = m_MatchCount+1; + m_GameInfo.m_MatchNum = (str_length(Config()->m_SvMaprotation) && Config()->m_SvMatchesPerMap) ? Config()->m_SvMatchesPerMap : 0; + m_GameInfo.m_ScoreLimit = Config()->m_SvScorelimit; + m_GameInfo.m_TimeLimit = Config()->m_SvTimelimit; + + // map + m_aMapWish[0] = 0; + + // spawn + m_aNumSpawnPoints[0] = 0; + m_aNumSpawnPoints[1] = 0; + m_aNumSpawnPoints[2] = 0; +} + +//activity +void IGameController::DoActivityCheck() +{ + if(Config()->m_SvInactiveKickTime == 0) + return; + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && !GameServer()->m_apPlayers[i]->IsDummy() && (GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS || Config()->m_SvInactiveKick > 0) && + !Server()->IsAuthed(i) && (GameServer()->m_apPlayers[i]->m_InactivityTickCounter > Config()->m_SvInactiveKickTime*Server()->TickSpeed()*60)) + { + if(GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) + { + if(Config()->m_SvInactiveKickSpec) + Server()->Kick(i, "Kicked for inactivity"); + } + else + { + switch(Config()->m_SvInactiveKick) + { + case 1: + { + // move player to spectator + DoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS); + } + break; + case 2: + { + // move player to spectator if the reserved slots aren't filled yet, kick him otherwise + int Spectators = 0; + for(int j = 0; j < MAX_CLIENTS; ++j) + if(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS) + ++Spectators; + if(Spectators >= Config()->m_SvMaxClients - Config()->m_SvPlayerSlots) + Server()->Kick(i, "Kicked for inactivity"); + else + DoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS); + } + break; + case 3: + { + // kick the player + Server()->Kick(i, "Kicked for inactivity"); + } + } + } + } + } +} + +bool IGameController::GetPlayersReadyState(int WithoutID) +{ + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == WithoutID) + continue; // skip + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !GameServer()->m_apPlayers[i]->m_IsReadyToPlay) + return false; + } + + return true; +} + +void IGameController::SetPlayersReadyState(bool ReadyState) +{ + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (ReadyState || !GameServer()->m_apPlayers[i]->m_DeadSpecMode)) + GameServer()->m_apPlayers[i]->m_IsReadyToPlay = ReadyState; + } +} + +// balancing +bool IGameController::CanBeMovedOnBalance(int ClientID) const +{ + return true; +} + +void IGameController::CheckTeamBalance() +{ + if(!IsTeamplay() || !Config()->m_SvTeambalanceTime) + { + m_UnbalancedTick = TBALANCE_OK; + return; + } + + // check if teams are unbalanced + char aBuf[256]; + if(absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) >= NUM_TEAMS) + { + str_format(aBuf, sizeof(aBuf), "Teams are NOT balanced (red=%d blue=%d)", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]); + if(m_UnbalancedTick <= TBALANCE_OK) + m_UnbalancedTick = Server()->Tick(); + } + else + { + str_format(aBuf, sizeof(aBuf), "Teams are balanced (red=%d blue=%d)", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]); + m_UnbalancedTick = TBALANCE_OK; + } + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); +} + +void IGameController::DoTeamBalance() +{ + if(!IsTeamplay() || !Config()->m_SvTeambalanceTime || absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) < NUM_TEAMS) + return; + + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "Balancing teams"); + + float aTeamScore[NUM_TEAMS] = {0}; + float aPlayerScore[MAX_CLIENTS] = {0.0f}; + + // gather stats + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + { + aPlayerScore[i] = GameServer()->m_apPlayers[i]->m_Score*Server()->TickSpeed()*60.0f/ + (Server()->Tick()-GameServer()->m_apPlayers[i]->m_ScoreStartTick); + aTeamScore[GameServer()->m_apPlayers[i]->GetTeam()] += aPlayerScore[i]; + } + } + + int BiggerTeam = (m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE]) ? TEAM_RED : TEAM_BLUE; + int NumBalance = absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) / NUM_TEAMS; + + // balance teams + do + { + CPlayer *pPlayer = 0; + float ScoreDiff = aTeamScore[BiggerTeam]; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!GameServer()->m_apPlayers[i] || !CanBeMovedOnBalance(i)) + continue; + + // remember the player whom would cause lowest score-difference + if(GameServer()->m_apPlayers[i]->GetTeam() == BiggerTeam && + (!pPlayer || absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i])) < ScoreDiff)) + { + pPlayer = GameServer()->m_apPlayers[i]; + ScoreDiff = absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i])); + } + } + + // move the player to the other team + if(pPlayer) + { + int Temp = pPlayer->m_LastActionTick; + DoTeamChange(pPlayer, BiggerTeam^1); + pPlayer->m_LastActionTick = Temp; + pPlayer->Respawn(); + GameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE_VICTIM, pPlayer->GetTeam(), pPlayer->GetCID()); + } + } + while(--NumBalance); + + m_UnbalancedTick = TBALANCE_OK; + GameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE, -1); +} + +// event +int IGameController::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int Weapon) +{ + // do scoreing + if(!pKiller || Weapon == WEAPON_GAME) + return 0; + if(pKiller == pVictim->GetPlayer()) + pVictim->GetPlayer()->m_Score--; // suicide or world + else + { + if(IsTeamplay() && pVictim->GetPlayer()->GetTeam() == pKiller->GetTeam()) + pKiller->m_Score--; // teamkill + else + pKiller->m_Score++; // normal kill + } + if(Weapon == WEAPON_SELF) + pVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f; + + + // update spectator modes for dead players in survival + if(m_GameFlags&GAMEFLAG_SURVIVAL) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_DeadSpecMode) + GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); + } + + return 0; +} + +void IGameController::OnCharacterSpawn(CCharacter *pChr) +{ + // default health + pChr->IncreaseHealth(10); + + // give default weapons + pChr->GiveWeapon(WEAPON_HAMMER, -1); + pChr->GiveWeapon(WEAPON_GUN, 10); +} + +void IGameController::OnFlagReturn(CFlag *pFlag) +{ +} + +bool IGameController::OnEntity(int Index, vec2 Pos) +{ + // don't add pickups in survival + if(m_GameFlags&GAMEFLAG_SURVIVAL) + { + if(Index < ENTITY_SPAWN || Index > ENTITY_SPAWN_BLUE) + return false; + } + + int Type = -1; + + switch(Index) + { + case ENTITY_SPAWN: + m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos; + break; + case ENTITY_SPAWN_RED: + m_aaSpawnPoints[1][m_aNumSpawnPoints[1]++] = Pos; + break; + case ENTITY_SPAWN_BLUE: + m_aaSpawnPoints[2][m_aNumSpawnPoints[2]++] = Pos; + break; + case ENTITY_ARMOR_1: + Type = PICKUP_ARMOR; + break; + case ENTITY_HEALTH_1: + Type = PICKUP_HEALTH; + break; + case ENTITY_WEAPON_SHOTGUN: + Type = PICKUP_SHOTGUN; + break; + case ENTITY_WEAPON_GRENADE: + Type = PICKUP_GRENADE; + break; + case ENTITY_WEAPON_LASER: + Type = PICKUP_LASER; + break; + case ENTITY_POWERUP_NINJA: + if(Config()->m_SvPowerups) + Type = PICKUP_NINJA; + } + + if(Type != -1) + { + new CPickup(&GameServer()->m_World, Type, Pos); + return true; + } + + return false; +} + +void IGameController::OnPlayerConnect(CPlayer *pPlayer) +{ + int ClientID = pPlayer->GetCID(); + pPlayer->Respawn(); + + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' team=%d", ClientID, Server()->ClientName(ClientID), pPlayer->GetTeam()); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + + // update game info + UpdateGameInfo(ClientID); +} + +void IGameController::OnPlayerDisconnect(CPlayer *pPlayer) +{ + pPlayer->OnDisconnect(); + + int ClientID = pPlayer->GetCID(); + if(Server()->ClientIngame(ClientID)) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "leave player='%d:%s'", ClientID, Server()->ClientName(ClientID)); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "game", aBuf); + } + + if(pPlayer->GetTeam() != TEAM_SPECTATORS) + { + --m_aTeamSize[pPlayer->GetTeam()]; + m_UnbalancedTick = TBALANCE_CHECK; + } + + CheckReadyStates(ClientID); +} + +void IGameController::OnPlayerInfoChange(CPlayer *pPlayer) +{ +} + +void IGameController::OnPlayerReadyChange(CPlayer *pPlayer) +{ + if(Config()->m_SvPlayerReadyMode && pPlayer->GetTeam() != TEAM_SPECTATORS && !pPlayer->m_DeadSpecMode) + { + // change players ready state + pPlayer->m_IsReadyToPlay ^= 1; + + if(m_GameState == IGS_GAME_RUNNING && !pPlayer->m_IsReadyToPlay) + { + SetGameState(IGS_GAME_PAUSED, TIMER_INFINITE); // one player isn't ready -> pause the game + GameServer()->SendGameMsg(GAMEMSG_GAME_PAUSED, pPlayer->GetCID(), -1); + } + + CheckReadyStates(); + } +} + +// to be called when a player changes state, spectates or disconnects +void IGameController::CheckReadyStates(int WithoutID) +{ + if(Config()->m_SvPlayerReadyMode) + { + switch(m_GameState) + { + case IGS_WARMUP_USER: + // all players are ready -> end warmup + if(GetPlayersReadyState(WithoutID)) + SetGameState(IGS_WARMUP_USER, 0); + break; + case IGS_GAME_PAUSED: + // all players are ready -> unpause the game + if(GetPlayersReadyState(WithoutID)) + SetGameState(IGS_GAME_PAUSED, 0); + break; + case IGS_GAME_RUNNING: + case IGS_WARMUP_GAME: + case IGS_START_COUNTDOWN: + case IGS_END_MATCH: + case IGS_END_ROUND: + // not affected + break; + } + } +} + +void IGameController::OnReset() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i]) + { + GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; + GameServer()->m_apPlayers[i]->Respawn(); + GameServer()->m_apPlayers[i]->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; + if(m_RoundCount == 0) + { + GameServer()->m_apPlayers[i]->m_Score = 0; + GameServer()->m_apPlayers[i]->m_ScoreStartTick = Server()->Tick(); + } + GameServer()->m_apPlayers[i]->m_IsReadyToPlay = true; + } + } +} + +// game +bool IGameController::DoWincheckMatch() +{ + if(IsTeamplay()) + { + // check score win condition + if((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) || + (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) + { + if(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE] || m_GameFlags&GAMEFLAG_SURVIVAL) + { + EndMatch(); + return true; + } + else + m_SuddenDeath = 1; + } + } + else + { + // gather some stats + int Topscore = 0; + int TopscoreCount = 0; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i]) + { + if(GameServer()->m_apPlayers[i]->m_Score > Topscore) + { + Topscore = GameServer()->m_apPlayers[i]->m_Score; + TopscoreCount = 1; + } + else if(GameServer()->m_apPlayers[i]->m_Score == Topscore) + TopscoreCount++; + } + } + + // check score win condition + if((m_GameInfo.m_ScoreLimit > 0 && Topscore >= m_GameInfo.m_ScoreLimit) || + (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) + { + if(TopscoreCount == 1) + { + EndMatch(); + return true; + } + else + m_SuddenDeath = 1; + } + } + return false; +} + +void IGameController::ResetGame() +{ + // reset the game + GameServer()->m_World.m_ResetRequested = true; + + SetGameState(IGS_GAME_RUNNING); + m_GameStartTick = Server()->Tick(); + m_SuddenDeath = 0; + + CheckGameInfo(); + + // do team-balancing + DoTeamBalance(); +} + +void IGameController::SetGameState(EGameState GameState, int Timer) +{ + // change game state + switch(GameState) + { + case IGS_WARMUP_GAME: + // game based warmup is only possible when game or any warmup is running + if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER) + { + if(Timer == TIMER_INFINITE) + { + // run warmup till there're enough players + m_GameState = GameState; + m_GameStateTimer = TIMER_INFINITE; + + // enable respawning in survival when activating warmup + if(m_GameFlags&GAMEFLAG_SURVIVAL) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + if(GameServer()->m_apPlayers[i]) + GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; + } + } + else if(Timer == 0) + { + // start new match + StartMatch(); + } + } + break; + case IGS_WARMUP_USER: + // user based warmup is only possible when the game or any warmup is running + if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER) + { + if(Timer != 0) + { + // start warmup + if(Timer < 0) + { + m_GameState = GameState; + m_GameStateTimer = TIMER_INFINITE; + if(Config()->m_SvPlayerReadyMode) + { + // run warmup till all players are ready + SetPlayersReadyState(false); + } + } + else if(Timer > 0) + { + // run warmup for a specific time intervall + m_GameState = GameState; + m_GameStateTimer = Timer*Server()->TickSpeed(); + } + + // enable respawning in survival when activating warmup + if(m_GameFlags&GAMEFLAG_SURVIVAL) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + if(GameServer()->m_apPlayers[i]) + GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; + } + GameServer()->m_World.m_Paused = false; + } + else + { + // start new match + StartMatch(); + } + } + break; + case IGS_START_COUNTDOWN: + // only possible when game, pause or start countdown is running + if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN) + { + if(Config()->m_SvCountdown == 0 && m_GameFlags&GAMEFLAG_SURVIVAL) + { + m_GameState = GameState; + m_GameStateTimer = 3*Server()->TickSpeed(); + GameServer()->m_World.m_Paused = true; + + } + else if(Config()->m_SvCountdown > 0) + { + m_GameState = GameState; + m_GameStateTimer = Config()->m_SvCountdown*Server()->TickSpeed(); + GameServer()->m_World.m_Paused = true; + } + else + { + // no countdown, start new match right away + SetGameState(IGS_GAME_RUNNING); + } + } + break; + case IGS_GAME_RUNNING: + // always possible + { + m_GameState = GameState; + m_GameStateTimer = TIMER_INFINITE; + SetPlayersReadyState(true); + GameServer()->m_World.m_Paused = false; + } + break; + case IGS_GAME_PAUSED: + // only possible when game is running or paused, or when game based warmup is running + if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_WARMUP_GAME) + { + if(Timer != 0) + { + // start pause + if(Timer < 0) + { + // pauses infinitely till all players are ready or disabled via rcon command + m_GameStateTimer = TIMER_INFINITE; + SetPlayersReadyState(false); + } + else + { + // pauses for a specific time interval + m_GameStateTimer = Timer*Server()->TickSpeed(); + } + + m_GameState = GameState; + GameServer()->m_World.m_Paused = true; + } + else + { + // start a countdown to end pause + SetGameState(IGS_START_COUNTDOWN); + } + } + break; + case IGS_END_ROUND: + case IGS_END_MATCH: + if(GameState == IGS_END_ROUND && DoWincheckMatch()) + break; + // only possible when game is running or over + if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_END_MATCH || m_GameState == IGS_END_ROUND || m_GameState == IGS_GAME_PAUSED) + { + m_GameState = GameState; + m_GameStateTimer = Timer*Server()->TickSpeed(); + m_SuddenDeath = 0; + GameServer()->m_World.m_Paused = true; + } + } +} + +void IGameController::StartMatch() +{ + ResetGame(); + + m_RoundCount = 0; + m_aTeamscore[TEAM_RED] = 0; + m_aTeamscore[TEAM_BLUE] = 0; + + // start countdown if there're enough players, otherwise do warmup till there're + if(HasEnoughPlayers()) + SetGameState(IGS_START_COUNTDOWN); + else + SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); + + Server()->DemoRecorder_HandleAutoStart(); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "start match type='%s' teamplay='%d'", m_pGameType, m_GameFlags&GAMEFLAG_TEAMS); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); +} + +void IGameController::StartRound() +{ + ResetGame(); + + ++m_RoundCount; + + // start countdown if there're enough players, otherwise abort to warmup + if(HasEnoughPlayers()) + SetGameState(IGS_START_COUNTDOWN); + else + SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); +} + +void IGameController::SwapTeamscore() +{ + if(!IsTeamplay()) + return; + + int Score = m_aTeamscore[TEAM_RED]; + m_aTeamscore[TEAM_RED] = m_aTeamscore[TEAM_BLUE]; + m_aTeamscore[TEAM_BLUE] = Score; +} + +// general +void IGameController::Snap(int SnappingClient) +{ + CNetObj_GameData *pGameData = static_cast(Server()->SnapNewItem(NETOBJTYPE_GAMEDATA, 0, sizeof(CNetObj_GameData))); + if(!pGameData) + return; + + pGameData->m_GameStartTick = m_GameStartTick; + pGameData->m_GameStateFlags = 0; + pGameData->m_GameStateEndTick = 0; // no timer/infinite = 0, on end = GameEndTick, otherwise = GameStateEndTick + switch(m_GameState) + { + case IGS_WARMUP_GAME: + case IGS_WARMUP_USER: + pGameData->m_GameStateFlags |= GAMESTATEFLAG_WARMUP; + if(m_GameStateTimer != TIMER_INFINITE) + pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; + break; + case IGS_START_COUNTDOWN: + pGameData->m_GameStateFlags |= GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED; + if(m_GameStateTimer != TIMER_INFINITE) + pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; + break; + case IGS_GAME_PAUSED: + pGameData->m_GameStateFlags |= GAMESTATEFLAG_PAUSED; + if(m_GameStateTimer != TIMER_INFINITE) + pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; + break; + case IGS_END_ROUND: + pGameData->m_GameStateFlags |= GAMESTATEFLAG_ROUNDOVER; + pGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END/2*Server()->TickSpeed()+m_GameStateTimer; + break; + case IGS_END_MATCH: + pGameData->m_GameStateFlags |= GAMESTATEFLAG_GAMEOVER; + pGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END*Server()->TickSpeed()+m_GameStateTimer; + break; + case IGS_GAME_RUNNING: + // not effected + break; + } + if(m_SuddenDeath) + pGameData->m_GameStateFlags |= GAMESTATEFLAG_SUDDENDEATH; + + if(IsTeamplay()) + { + CNetObj_GameDataTeam *pGameDataTeam = static_cast(Server()->SnapNewItem(NETOBJTYPE_GAMEDATATEAM, 0, sizeof(CNetObj_GameDataTeam))); + if(!pGameDataTeam) + return; + + pGameDataTeam->m_TeamscoreRed = m_aTeamscore[TEAM_RED]; + pGameDataTeam->m_TeamscoreBlue = m_aTeamscore[TEAM_BLUE]; + } + + // demo recording + if(SnappingClient == -1) + { + CNetObj_De_GameInfo *pGameInfo = static_cast(Server()->SnapNewItem(NETOBJTYPE_DE_GAMEINFO, 0, sizeof(CNetObj_De_GameInfo))); + if(!pGameInfo) + return; + + pGameInfo->m_GameFlags = m_GameFlags; + pGameInfo->m_ScoreLimit = m_GameInfo.m_ScoreLimit; + pGameInfo->m_TimeLimit = m_GameInfo.m_TimeLimit; + pGameInfo->m_MatchNum = m_GameInfo.m_MatchNum; + pGameInfo->m_MatchCurrent = m_GameInfo.m_MatchCurrent; + } +} + +void IGameController::Tick() +{ + // handle game states + if(m_GameState != IGS_GAME_RUNNING) + { + if(m_GameStateTimer > 0) + --m_GameStateTimer; + + if(m_GameStateTimer == 0) + { + // timer fires + switch(m_GameState) + { + case IGS_WARMUP_USER: + // end warmup + SetGameState(IGS_WARMUP_USER, 0); + break; + case IGS_START_COUNTDOWN: + // unpause the game + SetGameState(IGS_GAME_RUNNING); + break; + case IGS_GAME_PAUSED: + // end pause + SetGameState(IGS_GAME_PAUSED, 0); + break; + case IGS_END_ROUND: + StartRound(); + break; + case IGS_END_MATCH: + // start next match + if(m_MatchCount >= m_GameInfo.m_MatchNum-1) + CycleMap(); + + if(Config()->m_SvMatchSwap) + GameServer()->SwapTeams(); + m_MatchCount++; + StartMatch(); + break; + case IGS_WARMUP_GAME: + case IGS_GAME_RUNNING: + // not effected + break; + } + } + else + { + // timer still running + switch(m_GameState) + { + case IGS_WARMUP_USER: + // check if player ready mode was disabled and it waits that all players are ready -> end warmup + if(!Config()->m_SvPlayerReadyMode && m_GameStateTimer == TIMER_INFINITE) + SetGameState(IGS_WARMUP_USER, 0); + break; + case IGS_START_COUNTDOWN: + case IGS_GAME_PAUSED: + // freeze the game + ++m_GameStartTick; + break; + case IGS_WARMUP_GAME: + case IGS_GAME_RUNNING: + case IGS_END_MATCH: + case IGS_END_ROUND: + // not effected + break; + } + } + } + + // do team-balancing (skip this in survival, done there when a round starts) + if(IsTeamplay() && !(m_GameFlags&GAMEFLAG_SURVIVAL)) + { + switch(m_UnbalancedTick) + { + case TBALANCE_CHECK: + CheckTeamBalance(); + break; + case TBALANCE_OK: + break; + default: + if(Server()->Tick() > m_UnbalancedTick+Config()->m_SvTeambalanceTime*Server()->TickSpeed()*60) + DoTeamBalance(); + } + } + + // check for inactive players + DoActivityCheck(); + + // win check + if((m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED) && !GameServer()->m_World.m_ResetRequested) + { + if(m_GameFlags&GAMEFLAG_SURVIVAL) + DoWincheckRound(); + else + DoWincheckMatch(); + } +} + +// info +void IGameController::CheckGameInfo() +{ + int MatchNum = (str_length(Config()->m_SvMaprotation) && Config()->m_SvMatchesPerMap) ? Config()->m_SvMatchesPerMap : 0; + if(MatchNum == 0) + m_MatchCount = 0; + bool GameInfoChanged = (m_GameInfo.m_MatchCurrent != m_MatchCount + 1) || (m_GameInfo.m_MatchNum != MatchNum) || + (m_GameInfo.m_ScoreLimit != Config()->m_SvScorelimit) || (m_GameInfo.m_TimeLimit != Config()->m_SvTimelimit); + m_GameInfo.m_MatchCurrent = m_MatchCount + 1; + m_GameInfo.m_MatchNum = MatchNum; + m_GameInfo.m_ScoreLimit = Config()->m_SvScorelimit; + m_GameInfo.m_TimeLimit = Config()->m_SvTimelimit; + if(GameInfoChanged) + UpdateGameInfo(-1); +} + +bool IGameController::IsFriendlyFire(int ClientID1, int ClientID2) const +{ + if(ClientID1 == ClientID2) + return false; + + if(IsTeamplay()) + { + if(!GameServer()->m_apPlayers[ClientID1] || !GameServer()->m_apPlayers[ClientID2]) + return false; + + if(!Config()->m_SvTeamdamage && GameServer()->m_apPlayers[ClientID1]->GetTeam() == GameServer()->m_apPlayers[ClientID2]->GetTeam()) + return true; + } + + return false; +} + +bool IGameController::IsFriendlyTeamFire(int Team1, int Team2) const +{ + return IsTeamplay() && !Config()->m_SvTeamdamage && Team1 == Team2; +} + +bool IGameController::IsPlayerReadyMode() const +{ + return Config()->m_SvPlayerReadyMode != 0 && (m_GameStateTimer == TIMER_INFINITE && (m_GameState == IGS_WARMUP_USER || m_GameState == IGS_GAME_PAUSED)); +} + +bool IGameController::IsTeamChangeAllowed() const +{ + return !GameServer()->m_World.m_Paused || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick()); +} + +void IGameController::UpdateGameInfo(int ClientID) +{ + CNetMsg_Sv_GameInfo GameInfoMsg; + GameInfoMsg.m_GameFlags = m_GameFlags; + GameInfoMsg.m_ScoreLimit = m_GameInfo.m_ScoreLimit; + GameInfoMsg.m_TimeLimit = m_GameInfo.m_TimeLimit; + GameInfoMsg.m_MatchNum = m_GameInfo.m_MatchNum; + GameInfoMsg.m_MatchCurrent = m_GameInfo.m_MatchCurrent; + + CNetMsg_Sv_GameInfo GameInfoMsgNoRace = GameInfoMsg; + GameInfoMsgNoRace.m_GameFlags &= ~GAMEFLAG_RACE; + + if(ClientID == -1) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(!GameServer()->m_apPlayers[i] || !Server()->ClientIngame(i)) + continue; + + CNetMsg_Sv_GameInfo *pInfoMsg = (Server()->GetClientVersion(i) < CGameContext::MIN_RACE_CLIENTVERSION) ? &GameInfoMsgNoRace : &GameInfoMsg; + Server()->SendPackMsg(pInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + } + else + { + CNetMsg_Sv_GameInfo *pInfoMsg = (Server()->GetClientVersion(ClientID) < CGameContext::MIN_RACE_CLIENTVERSION) ? &GameInfoMsgNoRace : &GameInfoMsg; + Server()->SendPackMsg(pInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + } +} + +// map +static bool IsSeparator(char c) { return c == ';' || c == ' ' || c == ',' || c == '\t'; } + +void IGameController::ChangeMap(const char *pToMap) +{ + str_copy(m_aMapWish, pToMap, sizeof(m_aMapWish)); + + m_MatchCount = m_GameInfo.m_MatchNum-1; + SetGameState(IGS_GAME_RUNNING); + EndMatch(); +} + +void IGameController::CycleMap() +{ + if(m_aMapWish[0] != 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "rotating map to %s", m_aMapWish); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + Server()->ChangeMap(m_aMapWish); + + m_aMapWish[0] = 0; + m_MatchCount = 0; + return; + } + if(!str_length(Config()->m_SvMaprotation)) + return; + + // handle maprotation + const char *pMapRotation = Config()->m_SvMaprotation; + const char *pCurrentMap = Config()->m_SvMap; + + int CurrentMapLen = str_length(pCurrentMap); + const char *pNextMap = pMapRotation; + while(*pNextMap) + { + int WordLen = 0; + while(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen])) + WordLen++; + + if(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0) + { + // map found + pNextMap += CurrentMapLen; + while(*pNextMap && IsSeparator(*pNextMap)) + pNextMap++; + + break; + } + + pNextMap++; + } + + // restart rotation + if(pNextMap[0] == 0) + pNextMap = pMapRotation; + + // cut out the next map + char aBuf[512] = {0}; + for(int i = 0; i < 511; i++) + { + aBuf[i] = pNextMap[i]; + if(IsSeparator(pNextMap[i]) || pNextMap[i] == 0) + { + aBuf[i] = 0; + break; + } + } + + // skip spaces + int i = 0; + while(IsSeparator(aBuf[i])) + i++; + + m_MatchCount = 0; + + char aBufMsg[256]; + str_format(aBufMsg, sizeof(aBufMsg), "rotating map to %s", &aBuf[i]); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + Server()->ChangeMap(&aBuf[i]); +} + +// spawn +bool IGameController::CanSpawn(int Team, vec2 *pOutPos) const +{ + // spectators can't spawn + if(Team == TEAM_SPECTATORS || GameServer()->m_World.m_Paused || GameServer()->m_World.m_ResetRequested) + return false; + + CSpawnEval Eval; + Eval.m_RandomSpawn = IsSurvival(); + + if(IsTeamplay()) + { + Eval.m_FriendlyTeam = Team; + + // first try own team spawn, then normal spawn and then enemy + EvaluateSpawnType(&Eval, 1+(Team&1)); + if(!Eval.m_Got) + { + EvaluateSpawnType(&Eval, 0); + if(!Eval.m_Got) + EvaluateSpawnType(&Eval, 1+((Team+1)&1)); + } + } + else + { + EvaluateSpawnType(&Eval, 0); + EvaluateSpawnType(&Eval, 1); + EvaluateSpawnType(&Eval, 2); + } + + *pOutPos = Eval.m_Pos; + return Eval.m_Got; +} + +float IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const +{ + float Score = 0.0f; + CCharacter *pC = static_cast(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); + for(; pC; pC = (CCharacter *)pC->TypeNext()) + { + // team mates are not as dangerous as enemies + float Scoremod = 1.0f; + if(pEval->m_FriendlyTeam != -1 && pC->GetPlayer()->GetTeam() == pEval->m_FriendlyTeam) + Scoremod = 0.5f; + + float d = distance(Pos, pC->GetPos()); + Score += Scoremod * (d == 0 ? 1000000000.0f : 1.0f/d); + } + + return Score; +} + +void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) const +{ + // get spawn point + for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) + { + // check if the position is occupado + CCharacter *aEnts[MAX_CLIENTS]; + int Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + vec2 Positions[5] = { vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f) }; // start, left, up, right, down + int Result = -1; + for(int Index = 0; Index < 5 && Result == -1; ++Index) + { + Result = Index; + for(int c = 0; c < Num; ++c) + if(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i]+Positions[Index]) || + distance(aEnts[c]->GetPos(), m_aaSpawnPoints[Type][i]+Positions[Index]) <= aEnts[c]->GetProximityRadius()) + { + Result = -1; + break; + } + } + if(Result == -1) + continue; // try next spawn point + + vec2 P = m_aaSpawnPoints[Type][i]+Positions[Result]; + float S = pEval->m_RandomSpawn ? (Result + random_float()) : EvaluateSpawnPos(pEval, P); + if(!pEval->m_Got || pEval->m_Score > S) + { + pEval->m_Got = true; + pEval->m_Score = S; + pEval->m_Pos = P; + } + } +} + +bool IGameController::GetStartRespawnState() const +{ + if(m_GameFlags&GAMEFLAG_SURVIVAL) + { + // players can always respawn during warmup or match/round start countdown + if(m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick())) + return false; + else + return true; + } + else + return false; +} + +// team +bool IGameController::CanChangeTeam(CPlayer *pPlayer, int JoinTeam) const +{ + if(!IsTeamplay() || JoinTeam == TEAM_SPECTATORS || !Config()->m_SvTeambalanceTime) + return true; + + // simulate what would happen if the player changes team + int aPlayerCount[NUM_TEAMS] = { m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE] }; + aPlayerCount[JoinTeam]++; + if(pPlayer->GetTeam() != TEAM_SPECTATORS) + aPlayerCount[JoinTeam^1]--; + + // check if the player-difference decreases or is smaller than 2 + return aPlayerCount[JoinTeam]-aPlayerCount[JoinTeam^1] < NUM_TEAMS; +} + +bool IGameController::CanJoinTeam(int Team, int NotThisID) const +{ + if(Team == TEAM_SPECTATORS) + return true; + + // check if there're enough player slots left + int TeamMod = GameServer()->m_apPlayers[NotThisID] && GameServer()->m_apPlayers[NotThisID]->GetTeam() != TEAM_SPECTATORS ? -1 : 0; + return TeamMod+m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Config()->m_SvPlayerSlots; +} + +int IGameController::ClampTeam(int Team) const +{ + if(Team < TEAM_RED) + return TEAM_SPECTATORS; + if(IsTeamplay()) + return Team&1; + return TEAM_RED; +} + +void IGameController::DoTeamChange(CPlayer *pPlayer, int Team, bool DoChatMsg) +{ + Team = ClampTeam(Team); + if(Team == pPlayer->GetTeam()) + return; + + int OldTeam = pPlayer->GetTeam(); + pPlayer->SetTeam(Team); + + int ClientID = pPlayer->GetCID(); + + // notify clients + CNetMsg_Sv_Team Msg; + Msg.m_ClientID = ClientID; + Msg.m_Team = Team; + Msg.m_Silent = DoChatMsg ? 0 : 1; + Msg.m_CooldownTick = pPlayer->m_TeamChangeTick; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); + + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' team=%d->%d", ClientID, Server()->ClientName(ClientID), OldTeam, Team); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + + // update effected game settings + if(OldTeam != TEAM_SPECTATORS) + { + --m_aTeamSize[OldTeam]; + m_UnbalancedTick = TBALANCE_CHECK; + } + if(Team != TEAM_SPECTATORS) + { + ++m_aTeamSize[Team]; + m_UnbalancedTick = TBALANCE_CHECK; + if(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers()) + SetGameState(IGS_WARMUP_GAME, 0); + pPlayer->m_IsReadyToPlay = !IsPlayerReadyMode(); + if(m_GameFlags&GAMEFLAG_SURVIVAL) + pPlayer->m_RespawnDisabled = GetStartRespawnState(); + } + OnPlayerInfoChange(pPlayer); + GameServer()->OnClientTeamChange(ClientID); + CheckReadyStates(); + + // reset inactivity counter when joining the game + if(OldTeam == TEAM_SPECTATORS) + pPlayer->m_InactivityTickCounter = 0; +} + +int IGameController::GetStartTeam() +{ + if(Config()->m_SvTournamentMode) + return TEAM_SPECTATORS; + + // determine new team + int Team = TEAM_RED; + if(IsTeamplay()) + { + if(!Config()->m_DbgStress) // this will force the auto balancer to work overtime aswell + Team = m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE] ? TEAM_BLUE : TEAM_RED; + } + + // check if there're enough player slots left + if(m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Config()->m_SvPlayerSlots) + { + ++m_aTeamSize[Team]; + m_UnbalancedTick = TBALANCE_CHECK; + if(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers()) + SetGameState(IGS_WARMUP_GAME, 0); + return Team; + } + return TEAM_SPECTATORS; +} + +/*void IGameController::Com_Example(IConsole::IResult *pResult, void *pContext) +{ + CCommandManager::SCommandContext *pComContext = (CCommandManager::SCommandContext *)pContext; + IGameController *pSelf = (IGameController *)pComContext->m_pContext; + + pSelf->GameServer()->SendBroadcast(pResult->GetString(0), -1); +}*/ + +void IGameController::RegisterChatCommands(CCommandManager *pManager) +{ + //pManager->AddCommand("test", "Test the command system", "r", Com_Example, this); +} diff --git a/src/game/server/gamecontroller.h b/src/game/server/gamecontroller.h new file mode 100644 index 000000000..02c4bb389 --- /dev/null +++ b/src/game/server/gamecontroller.h @@ -0,0 +1,236 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMECONTROLLER_H +#define GAME_SERVER_GAMECONTROLLER_H + +#include +#include + +#include + +#include + +/* + Class: Game Controller + Controls the main game logic. Keeping track of team and player score, + winning conditions and specific game logic. +*/ +class IGameController +{ + class CGameContext *m_pGameServer; + class CConfig *m_pConfig; + class IServer *m_pServer; + + // activity + void DoActivityCheck(); + bool GetPlayersReadyState(int WithoutID = -1); + void SetPlayersReadyState(bool ReadyState); + void CheckReadyStates(int WithoutID = -1); + + // balancing + enum + { + TBALANCE_CHECK=-2, + TBALANCE_OK, + }; + int m_aTeamSize[NUM_TEAMS]; + int m_UnbalancedTick; + + virtual bool CanBeMovedOnBalance(int ClientID) const; + void CheckTeamBalance(); + void DoTeamBalance(); + + // game + enum EGameState + { + // internal game states + IGS_WARMUP_GAME, // warmup started by game because there're not enough players (infinite) + IGS_WARMUP_USER, // warmup started by user action via rcon or new match (infinite or timer) + + IGS_START_COUNTDOWN, // start countown to unpause the game or start match/round (tick timer) + + IGS_GAME_PAUSED, // game paused (infinite or tick timer) + IGS_GAME_RUNNING, // game running (infinite) + + IGS_END_MATCH, // match is over (tick timer) + IGS_END_ROUND, // round is over (tick timer) + }; + EGameState m_GameState; + int m_GameStateTimer; + + virtual bool DoWincheckMatch(); // returns true when the match is over + virtual void DoWincheckRound() {} + bool HasEnoughPlayers() const { return (IsTeamplay() && m_aTeamSize[TEAM_RED] > 0 && m_aTeamSize[TEAM_BLUE] > 0) || (!IsTeamplay() && m_aTeamSize[TEAM_RED] > 1); } + void ResetGame(); + void SetGameState(EGameState GameState, int Timer=0); + void StartMatch(); + void StartRound(); + + // map + char m_aMapWish[128]; + + void CycleMap(); + + // spawn + struct CSpawnEval + { + CSpawnEval() + { + m_Got = false; + m_FriendlyTeam = -1; + m_Pos = vec2(100,100); + } + + vec2 m_Pos; + bool m_Got; + bool m_RandomSpawn; + int m_FriendlyTeam; + float m_Score; + }; + vec2 m_aaSpawnPoints[3][64]; + int m_aNumSpawnPoints[3]; + + float EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const; + void EvaluateSpawnType(CSpawnEval *pEval, int Type) const; + + // team + int ClampTeam(int Team) const; + +protected: + CGameContext *GameServer() const { return m_pGameServer; } + CConfig *Config() const { return m_pConfig; } + IServer *Server() const { return m_pServer; } + + // game + int m_GameStartTick; + int m_MatchCount; + int m_RoundCount; + int m_SuddenDeath; + int m_aTeamscore[NUM_TEAMS]; + + void EndMatch() { SetGameState(IGS_END_MATCH, TIMER_END); } + void EndRound() { SetGameState(IGS_END_ROUND, TIMER_END/2); } + + // info + int m_GameFlags; + const char *m_pGameType; + struct CGameInfo + { + int m_MatchCurrent; + int m_MatchNum; + int m_ScoreLimit; + int m_TimeLimit; + } m_GameInfo; + + void UpdateGameInfo(int ClientID); + +public: + IGameController(class CGameContext *pGameServer); + virtual ~IGameController() {} + + // event + /* + Function: on_CCharacter_death + Called when a CCharacter in the world dies. + + Arguments: + victim - The CCharacter that died. + killer - The player that killed it. + weapon - What weapon that killed it. Can be -1 for undefined + weapon when switching team or player suicides. + */ + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + /* + Function: on_CCharacter_spawn + Called when a CCharacter spawns into the game world. + + Arguments: + chr - The CCharacter that was spawned. + */ + virtual void OnCharacterSpawn(class CCharacter *pChr); + + virtual void OnFlagReturn(class CFlag *pFlag); + + /* + Function: on_entity + Called when the map is loaded to process an entity + in the map. + + Arguments: + index - Entity index. + pos - Where the entity is located in the world. + + Returns: + bool? + */ + virtual bool OnEntity(int Index, vec2 Pos); + + virtual void OnPlayerConnect(class CPlayer *pPlayer); + virtual void OnPlayerDisconnect(class CPlayer *pPlayer); + virtual void OnPlayerInfoChange(class CPlayer *pPlayer); + virtual void OnPlayerReadyChange(class CPlayer *pPlayer); + void OnPlayerCommand(class CPlayer *pPlayer, const char *pCommandName, const char *pCommandArgs); + + void OnReset(); + + // game + enum + { + TIMER_INFINITE = -1, + TIMER_END = 10, + }; + + void DoPause(int Seconds) { SetGameState(IGS_GAME_PAUSED, Seconds); } + void DoWarmup(int Seconds) + { + SetGameState(IGS_WARMUP_USER, Seconds); + } + void AbortWarmup() + { + if((m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER) + && m_GameStateTimer != TIMER_INFINITE) + { + SetGameState(IGS_GAME_RUNNING); + } + } + void SwapTeamscore(); + + // general + virtual void Snap(int SnappingClient); + virtual void Tick(); + + // info + void CheckGameInfo(); + bool IsFriendlyFire(int ClientID1, int ClientID2) const; + bool IsFriendlyTeamFire(int Team1, int Team2) const; + bool IsGamePaused() const { return m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN; } + bool IsGameRunning() const { return m_GameState == IGS_GAME_RUNNING; } + bool IsPlayerReadyMode() const; + bool IsTeamChangeAllowed() const; + bool IsTeamplay() const { return m_GameFlags&GAMEFLAG_TEAMS; } + bool IsSurvival() const { return m_GameFlags&GAMEFLAG_SURVIVAL; } + + const char *GetGameType() const { return m_pGameType; } + + // map + void ChangeMap(const char *pToMap); + + //spawn + bool CanSpawn(int Team, vec2 *pPos) const; + bool GetStartRespawnState() const; + + // team + bool CanJoinTeam(int Team, int NotThisID) const; + bool CanChangeTeam(CPlayer *pPplayer, int JoinTeam) const; + + void DoTeamChange(class CPlayer *pPlayer, int Team, bool DoChatMsg=true); + void ForceTeamBalance() { if(!(m_GameFlags&GAMEFLAG_SURVIVAL)) DoTeamBalance(); } + + int GetRealPlayerNum() const { return m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE]; } + int GetStartTeam(); + + //static void Com_Example(IConsole::IResult *pResult, void *pContext); + virtual void RegisterChatCommands(CCommandManager *pManager); +}; + +#endif diff --git a/src/game/server/gamemodes/ctf.cpp b/src/game/server/gamemodes/ctf.cpp new file mode 100644 index 000000000..7d95b3120 --- /dev/null +++ b/src/game/server/gamemodes/ctf.cpp @@ -0,0 +1,255 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +#include +#include +#include +#include +#include "ctf.h" + +CGameControllerCTF::CGameControllerCTF(CGameContext *pGameServer) +: IGameController(pGameServer) +{ + // game + m_apFlags[0] = 0; + m_apFlags[1] = 0; + m_pGameType = "CTF"; + m_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_FLAGS; +} + +// balancing +bool CGameControllerCTF::CanBeMovedOnBalance(int ClientID) const +{ + CCharacter* Character = GameServer()->m_apPlayers[ClientID]->GetCharacter(); + if(Character) + { + for(int fi = 0; fi < 2; fi++) + { + CFlag *F = m_apFlags[fi]; + if(F && F->GetCarrier() == Character) + return false; + } + } + return true; +} + +// event +int CGameControllerCTF::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int WeaponID) +{ + IGameController::OnCharacterDeath(pVictim, pKiller, WeaponID); + int HadFlag = 0; + + // drop flags + for(int i = 0; i < 2; i++) + { + CFlag *F = m_apFlags[i]; + if(F && pKiller && pKiller->GetCharacter() && F->GetCarrier() == pKiller->GetCharacter()) + HadFlag |= 2; + if(F && F->GetCarrier() == pVictim) + { + GameServer()->SendGameMsg(GAMEMSG_CTF_DROP, -1); + F->Drop(); + + if(pKiller && pKiller->GetTeam() != pVictim->GetPlayer()->GetTeam()) + pKiller->m_Score++; + + HadFlag |= 1; + } + } + + return HadFlag; +} + +void CGameControllerCTF::OnFlagReturn(CFlag *pFlag) +{ + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "flag_return"); + GameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1); +} + +bool CGameControllerCTF::OnEntity(int Index, vec2 Pos) +{ + if(IGameController::OnEntity(Index, Pos)) + return true; + + int Team = -1; + if(Index == ENTITY_FLAGSTAND_RED) Team = TEAM_RED; + if(Index == ENTITY_FLAGSTAND_BLUE) Team = TEAM_BLUE; + if(Team == -1 || m_apFlags[Team]) + return false; + + CFlag *F = new CFlag(&GameServer()->m_World, Team, Pos); + m_apFlags[Team] = F; + return true; +} + +// game +bool CGameControllerCTF::DoWincheckMatch() +{ + // check score win condition + if((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) || + (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) + { + if(m_SuddenDeath) + { + if(m_aTeamscore[TEAM_RED]/100 != m_aTeamscore[TEAM_BLUE]/100) + { + EndMatch(); + return true; + } + } + else + { + if(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE]) + { + EndMatch(); + return true; + } + else + m_SuddenDeath = 1; + } + } + return false; +} + +// general +void CGameControllerCTF::Snap(int SnappingClient) +{ + IGameController::Snap(SnappingClient); + + CNetObj_GameDataFlag *pGameDataFlag = static_cast(Server()->SnapNewItem(NETOBJTYPE_GAMEDATAFLAG, 0, sizeof(CNetObj_GameDataFlag))); + if(!pGameDataFlag) + return; + + pGameDataFlag->m_FlagDropTickRed = 0; + if(m_apFlags[TEAM_RED]) + { + if(m_apFlags[TEAM_RED]->IsAtStand()) + pGameDataFlag->m_FlagCarrierRed = FLAG_ATSTAND; + else if(m_apFlags[TEAM_RED]->GetCarrier() && m_apFlags[TEAM_RED]->GetCarrier()->GetPlayer()) + pGameDataFlag->m_FlagCarrierRed = m_apFlags[TEAM_RED]->GetCarrier()->GetPlayer()->GetCID(); + else + { + pGameDataFlag->m_FlagCarrierRed = FLAG_TAKEN; + pGameDataFlag->m_FlagDropTickRed = m_apFlags[TEAM_RED]->GetDropTick(); + } + } + else + pGameDataFlag->m_FlagCarrierRed = FLAG_MISSING; + pGameDataFlag->m_FlagDropTickBlue = 0; + if(m_apFlags[TEAM_BLUE]) + { + if(m_apFlags[TEAM_BLUE]->IsAtStand()) + pGameDataFlag->m_FlagCarrierBlue = FLAG_ATSTAND; + else if(m_apFlags[TEAM_BLUE]->GetCarrier() && m_apFlags[TEAM_BLUE]->GetCarrier()->GetPlayer()) + pGameDataFlag->m_FlagCarrierBlue = m_apFlags[TEAM_BLUE]->GetCarrier()->GetPlayer()->GetCID(); + else + { + pGameDataFlag->m_FlagCarrierBlue = FLAG_TAKEN; + pGameDataFlag->m_FlagDropTickBlue = m_apFlags[TEAM_BLUE]->GetDropTick(); + } + } + else + pGameDataFlag->m_FlagCarrierBlue = FLAG_MISSING; +} + +void CGameControllerCTF::Tick() +{ + IGameController::Tick(); + + if(GameServer()->m_World.m_ResetRequested || GameServer()->m_World.m_Paused) + return; + + for(int fi = 0; fi < 2; fi++) + { + CFlag *F = m_apFlags[fi]; + + if(!F) + continue; + + // + if(F->GetCarrier()) + { + if(m_apFlags[fi^1] && m_apFlags[fi^1]->IsAtStand()) + { + if(distance(F->GetPos(), m_apFlags[fi^1]->GetPos()) < CFlag::ms_PhysSize + CCharacter::ms_PhysSize) + { + // CAPTURE! \o/ + m_aTeamscore[fi^1] += 100; + F->GetCarrier()->GetPlayer()->m_Score += 5; + float Diff = Server()->Tick() - F->GetGrabTick(); + + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "flag_capture player='%d:%s' team=%d time=%.2f", + F->GetCarrier()->GetPlayer()->GetCID(), + Server()->ClientName(F->GetCarrier()->GetPlayer()->GetCID()), + F->GetCarrier()->GetPlayer()->GetTeam(), + Diff / (float)Server()->TickSpeed() + ); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + + GameServer()->SendGameMsg(GAMEMSG_CTF_CAPTURE, fi, F->GetCarrier()->GetPlayer()->GetCID(), Diff, -1); + for(int i = 0; i < 2; i++) + m_apFlags[i]->Reset(); + // do a win check(capture could trigger win condition) + if(DoWincheckMatch()) + return; + } + } + } + else + { + CCharacter *apCloseCCharacters[MAX_CLIENTS]; + int Num = GameServer()->m_World.FindEntities(F->GetPos(), CFlag::ms_PhysSize, (CEntity**)apCloseCCharacters, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; i++) + { + if(!apCloseCCharacters[i]->IsAlive() || apCloseCCharacters[i]->GetPlayer()->GetTeam() == TEAM_SPECTATORS || GameServer()->Collision()->IntersectLine(F->GetPos(), apCloseCCharacters[i]->GetPos(), NULL, NULL)) + continue; + + if(apCloseCCharacters[i]->GetPlayer()->GetTeam() == F->GetTeam()) + { + // return the flag + if(!F->IsAtStand()) + { + CCharacter *pChr = apCloseCCharacters[i]; + pChr->GetPlayer()->m_Score += 1; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "flag_return player='%d:%s' team=%d", + pChr->GetPlayer()->GetCID(), + Server()->ClientName(pChr->GetPlayer()->GetCID()), + pChr->GetPlayer()->GetTeam() + ); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + GameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1); + F->Reset(); + } + } + else + { + // take the flag + if(F->IsAtStand()) + m_aTeamscore[fi^1]++; + + F->Grab(apCloseCCharacters[i]); + + F->GetCarrier()->GetPlayer()->m_Score += 1; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "flag_grab player='%d:%s' team=%d", + F->GetCarrier()->GetPlayer()->GetCID(), + Server()->ClientName(F->GetCarrier()->GetPlayer()->GetCID()), + F->GetCarrier()->GetPlayer()->GetTeam() + ); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + GameServer()->SendGameMsg(GAMEMSG_CTF_GRAB, fi, -1); + break; + } + } + } + } + // do a win check(grabbing flags could trigger win condition) + DoWincheckMatch(); +} diff --git a/src/game/server/gamemodes/ctf.h b/src/game/server/gamemodes/ctf.h new file mode 100644 index 000000000..578e41ccc --- /dev/null +++ b/src/game/server/gamemodes/ctf.h @@ -0,0 +1,32 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_CTF_H +#define GAME_SERVER_GAMEMODES_CTF_H +#include +#include + +class CGameControllerCTF : public IGameController +{ + // balancing + virtual bool CanBeMovedOnBalance(int ClientID) const; + + // game + class CFlag *m_apFlags[2]; + + virtual bool DoWincheckMatch(); + +public: + CGameControllerCTF(class CGameContext *pGameServer); + + // event + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + virtual void OnFlagReturn(class CFlag *pFlag); + virtual bool OnEntity(int Index, vec2 Pos); + + // general + virtual void Snap(int SnappingClient); + virtual void Tick(); +}; + +#endif + diff --git a/src/game/server/gamemodes/dm.cpp b/src/game/server/gamemodes/dm.cpp new file mode 100644 index 000000000..f4a309c93 --- /dev/null +++ b/src/game/server/gamemodes/dm.cpp @@ -0,0 +1,10 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "dm.h" + + +CGameControllerDM::CGameControllerDM(CGameContext *pGameServer) +: IGameController(pGameServer) +{ + m_pGameType = "DM"; +} diff --git a/src/game/server/gamemodes/dm.h b/src/game/server/gamemodes/dm.h new file mode 100644 index 000000000..6ec9adbe0 --- /dev/null +++ b/src/game/server/gamemodes/dm.h @@ -0,0 +1,13 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_DM_H +#define GAME_SERVER_GAMEMODES_DM_H +#include + +class CGameControllerDM : public IGameController +{ +public: + CGameControllerDM(class CGameContext *pGameServer); +}; + +#endif diff --git a/src/game/server/gamemodes/lms.cpp b/src/game/server/gamemodes/lms.cpp new file mode 100644 index 000000000..6c132016d --- /dev/null +++ b/src/game/server/gamemodes/lms.cpp @@ -0,0 +1,71 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include "lms.h" + +CGameControllerLMS::CGameControllerLMS(CGameContext *pGameServer) : IGameController(pGameServer) +{ + m_pGameType = "LMS"; + m_GameFlags = GAMEFLAG_SURVIVAL; +} + +// event +void CGameControllerLMS::OnCharacterSpawn(CCharacter *pChr) +{ + IGameController::OnCharacterSpawn(pChr); + + // give start equipment + pChr->IncreaseArmor(5); + pChr->GiveWeapon(WEAPON_SHOTGUN, 10); + pChr->GiveWeapon(WEAPON_GRENADE, 10); + pChr->GiveWeapon(WEAPON_LASER, 5); + + // prevent respawn + pChr->GetPlayer()->m_RespawnDisabled = GetStartRespawnState(); +} + +// game +void CGameControllerLMS::DoWincheckRound() +{ + // check for time based win + if(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && + (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || + (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) + GameServer()->m_apPlayers[i]->m_Score++; + } + + EndRound(); + } + else + { + // check for survival win + CPlayer *pAlivePlayer = 0; + int AlivePlayerCount = 0; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && + (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || + (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) + { + ++AlivePlayerCount; + pAlivePlayer = GameServer()->m_apPlayers[i]; + } + } + + if(AlivePlayerCount == 0) // no winner + EndRound(); + else if(AlivePlayerCount == 1) // 1 winner + { + pAlivePlayer->m_Score++; + EndRound(); + } + } +} diff --git a/src/game/server/gamemodes/lms.h b/src/game/server/gamemodes/lms.h new file mode 100644 index 000000000..1995bd26e --- /dev/null +++ b/src/game/server/gamemodes/lms.h @@ -0,0 +1,18 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_LMS_H +#define GAME_SERVER_GAMEMODES_LMS_H +#include + +class CGameControllerLMS : public IGameController +{ +public: + CGameControllerLMS(class CGameContext *pGameServer); + + // event + virtual void OnCharacterSpawn(class CCharacter *pChr); + // game + virtual void DoWincheckRound(); +}; + +#endif diff --git a/src/game/server/gamemodes/lts.cpp b/src/game/server/gamemodes/lts.cpp new file mode 100644 index 000000000..e60082ab1 --- /dev/null +++ b/src/game/server/gamemodes/lts.cpp @@ -0,0 +1,59 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include "lts.h" + +CGameControllerLTS::CGameControllerLTS(CGameContext *pGameServer) : IGameController(pGameServer) +{ + m_pGameType = "LTS"; + m_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_SURVIVAL; +} + +// event +void CGameControllerLTS::OnCharacterSpawn(class CCharacter *pChr) +{ + IGameController::OnCharacterSpawn(pChr); + + // give start equipment + pChr->IncreaseArmor(5); + pChr->GiveWeapon(WEAPON_SHOTGUN, 10); + pChr->GiveWeapon(WEAPON_GRENADE, 10); + pChr->GiveWeapon(WEAPON_LASER, 5); + + // prevent respawn + pChr->GetPlayer()->m_RespawnDisabled = GetStartRespawnState(); +} + +// game +void CGameControllerLTS::DoWincheckRound() +{ + int Count[2] = {0}; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && + (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || + (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) + ++Count[GameServer()->m_apPlayers[i]->GetTeam()]; + } + + if(Count[TEAM_RED]+Count[TEAM_BLUE] == 0 || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) + { + ++m_aTeamscore[TEAM_BLUE]; + ++m_aTeamscore[TEAM_RED]; + EndRound(); + } + else if(Count[TEAM_RED] == 0) + { + ++m_aTeamscore[TEAM_BLUE]; + EndRound(); + } + else if(Count[TEAM_BLUE] == 0) + { + ++m_aTeamscore[TEAM_RED]; + EndRound(); + } +} diff --git a/src/game/server/gamemodes/lts.h b/src/game/server/gamemodes/lts.h new file mode 100644 index 000000000..476b43dd5 --- /dev/null +++ b/src/game/server/gamemodes/lts.h @@ -0,0 +1,18 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_LTS_H +#define GAME_SERVER_GAMEMODES_LTS_H +#include + +class CGameControllerLTS : public IGameController +{ +public: + CGameControllerLTS(class CGameContext *pGameServer); + + // event + virtual void OnCharacterSpawn(class CCharacter *pChr); + // game + virtual void DoWincheckRound(); +}; + +#endif diff --git a/src/game/server/gamemodes/mod.cpp b/src/game/server/gamemodes/mod.cpp new file mode 100644 index 000000000..eb8fd7c81 --- /dev/null +++ b/src/game/server/gamemodes/mod.cpp @@ -0,0 +1,20 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "mod.h" + +CGameControllerMOD::CGameControllerMOD(class CGameContext *pGameServer) +: IGameController(pGameServer) +{ + // Exchange this to a string that identifies your game mode. + // DM, TDM and CTF are reserved for teeworlds original modes. + m_pGameType = "MOD"; + + //m_GameFlags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode +} + +void CGameControllerMOD::Tick() +{ + // this is the main part of the gamemode, this function is run every tick + + IGameController::Tick(); +} diff --git a/src/game/server/gamemodes/mod.h b/src/game/server/gamemodes/mod.h new file mode 100644 index 000000000..847d35f3d --- /dev/null +++ b/src/game/server/gamemodes/mod.h @@ -0,0 +1,16 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_MOD_H +#define GAME_SERVER_GAMEMODES_MOD_H +#include + +// you can subclass GAMECONTROLLER_CTF, GAMECONTROLLER_TDM etc if you want +// todo a modification with their base as well. +class CGameControllerMOD : public IGameController +{ +public: + CGameControllerMOD(class CGameContext *pGameServer); + virtual void Tick(); + // add more virtual functions here if you wish +}; +#endif diff --git a/src/game/server/gamemodes/tdm.cpp b/src/game/server/gamemodes/tdm.cpp new file mode 100644 index 000000000..9bf3db476 --- /dev/null +++ b/src/game/server/gamemodes/tdm.cpp @@ -0,0 +1,34 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include "tdm.h" + +CGameControllerTDM::CGameControllerTDM(class CGameContext *pGameServer) : IGameController(pGameServer) +{ + m_pGameType = "TDM"; + m_GameFlags = GAMEFLAG_TEAMS; +} + +// event +int CGameControllerTDM::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + IGameController::OnCharacterDeath(pVictim, pKiller, Weapon); + + + if(pKiller && Weapon != WEAPON_GAME) + { + // do team scoring + if(pKiller == pVictim->GetPlayer() || pKiller->GetTeam() == pVictim->GetPlayer()->GetTeam()) + m_aTeamscore[pKiller->GetTeam()&1]--; // klant arschel + else + m_aTeamscore[pKiller->GetTeam()&1]++; // good shit + } + + pVictim->GetPlayer()->m_RespawnTick = maximum(pVictim->GetPlayer()->m_RespawnTick, Server()->Tick()+Server()->TickSpeed()*Config()->m_SvRespawnDelayTDM); + + return 0; +} diff --git a/src/game/server/gamemodes/tdm.h b/src/game/server/gamemodes/tdm.h new file mode 100644 index 000000000..ea0cffdbb --- /dev/null +++ b/src/game/server/gamemodes/tdm.h @@ -0,0 +1,16 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEMODES_TDM_H +#define GAME_SERVER_GAMEMODES_TDM_H +#include + +class CGameControllerTDM : public IGameController +{ +public: + CGameControllerTDM(class CGameContext *pGameServer); + + // event + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); +}; + +#endif diff --git a/src/game/server/gameworld.cpp b/src/game/server/gameworld.cpp new file mode 100644 index 000000000..24f3de360 --- /dev/null +++ b/src/game/server/gameworld.cpp @@ -0,0 +1,261 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "entities/character.h" +#include "entity.h" +#include "gamecontext.h" +#include "gamecontroller.h" +#include "gameworld.h" + + +////////////////////////////////////////////////// +// game world +////////////////////////////////////////////////// +CGameWorld::CGameWorld() +{ + m_pGameServer = 0x0; + m_pConfig = 0x0; + m_pServer = 0x0; + + m_Paused = false; + m_ResetRequested = false; + for(int i = 0; i < NUM_ENTTYPES; i++) + m_apFirstEntityTypes[i] = 0; +} + +CGameWorld::~CGameWorld() +{ + // delete all entities + for(int i = 0; i < NUM_ENTTYPES; i++) + while(m_apFirstEntityTypes[i]) + delete m_apFirstEntityTypes[i]; +} + +void CGameWorld::SetGameServer(CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; + m_pConfig = m_pGameServer->Config(); + m_pServer = m_pGameServer->Server(); +} + +CEntity *CGameWorld::FindFirst(int Type) +{ + return Type < 0 || Type >= NUM_ENTTYPES ? 0 : m_apFirstEntityTypes[Type]; +} + +int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type) +{ + if(Type < 0 || Type >= NUM_ENTTYPES) + return 0; + + int Num = 0; + for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) + { + if(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius) + { + if(ppEnts) + ppEnts[Num] = pEnt; + Num++; + if(Num == Max) + break; + } + } + + return Num; +} + +void CGameWorld::InsertEntity(CEntity *pEnt) +{ +#ifdef CONF_DEBUG + for(CEntity *pCur = m_apFirstEntityTypes[pEnt->m_ObjType]; pCur; pCur = pCur->m_pNextTypeEntity) + dbg_assert(pCur != pEnt, "err"); +#endif + + // insert it + if(m_apFirstEntityTypes[pEnt->m_ObjType]) + m_apFirstEntityTypes[pEnt->m_ObjType]->m_pPrevTypeEntity = pEnt; + pEnt->m_pNextTypeEntity = m_apFirstEntityTypes[pEnt->m_ObjType]; + pEnt->m_pPrevTypeEntity = 0x0; + m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt; +} + +void CGameWorld::DestroyEntity(CEntity *pEnt) +{ + pEnt->MarkForDestroy(); +} + +void CGameWorld::RemoveEntity(CEntity *pEnt) +{ + // not in the list + if(!pEnt->m_pNextTypeEntity && !pEnt->m_pPrevTypeEntity && m_apFirstEntityTypes[pEnt->m_ObjType] != pEnt) + return; + + // remove + if(pEnt->m_pPrevTypeEntity) + pEnt->m_pPrevTypeEntity->m_pNextTypeEntity = pEnt->m_pNextTypeEntity; + else + m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt->m_pNextTypeEntity; + if(pEnt->m_pNextTypeEntity) + pEnt->m_pNextTypeEntity->m_pPrevTypeEntity = pEnt->m_pPrevTypeEntity; + + // keep list traversing valid + if(m_pNextTraverseEntity == pEnt) + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + + pEnt->m_pNextTypeEntity = 0; + pEnt->m_pPrevTypeEntity = 0; +} + +// +void CGameWorld::Snap(int SnappingClient) +{ + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Snap(SnappingClient); + pEnt = m_pNextTraverseEntity; + } +} + +void CGameWorld::PostSnap() +{ + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->PostSnap(); + pEnt = m_pNextTraverseEntity; + } +} + +void CGameWorld::Reset() +{ + // reset all entities + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Reset(); + pEnt = m_pNextTraverseEntity; + } + RemoveEntities(); + + GameServer()->m_pController->OnReset(); + RemoveEntities(); + + m_ResetRequested = false; +} + +void CGameWorld::RemoveEntities() +{ + // destroy objects marked for destruction + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + if(pEnt->IsMarkedForDestroy()) + { + RemoveEntity(pEnt); + pEnt->Destroy(); + } + pEnt = m_pNextTraverseEntity; + } +} + +void CGameWorld::Tick() +{ + if(m_ResetRequested) + Reset(); + + if(m_Paused || GameServer()->m_pController->IsGamePaused()) + { + // update all objects + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->TickPaused(); + pEnt = m_pNextTraverseEntity; + } + } + else + { + // update all objects + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Tick(); + pEnt = m_pNextTraverseEntity; + } + + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->TickDefered(); + pEnt = m_pNextTraverseEntity; + } + } + + RemoveEntities(); +} + + +// TODO: should be more general +CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CEntity *pNotThis) +{ + // Find other players + float ClosestLen = distance(Pos0, Pos1) * 100.0f; + CCharacter *pClosest = 0; + + CCharacter *p = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); + for(; p; p = (CCharacter *)p->TypeNext()) + { + if(p == pNotThis) + continue; + + vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos); + float Len = distance(p->m_Pos, IntersectPos); + if(Len < p->m_ProximityRadius+Radius) + { + Len = distance(Pos0, IntersectPos); + if(Len < ClosestLen) + { + NewPos = IntersectPos; + ClosestLen = Len; + pClosest = p; + } + } + } + + return pClosest; +} + + +CEntity *CGameWorld::ClosestEntity(vec2 Pos, float Radius, int Type, CEntity *pNotThis) +{ + // Find other players + float ClosestRange = Radius*2; + CEntity *pClosest = 0; + + CEntity *p = FindFirst(Type); + for(; p; p = p->TypeNext()) + { + if(p == pNotThis) + continue; + + float Len = distance(Pos, p->m_Pos); + if(Len < p->m_ProximityRadius+Radius) + { + if(Len < ClosestRange) + { + ClosestRange = Len; + pClosest = p; + } + } + } + + return pClosest; +} diff --git a/src/game/server/gameworld.h b/src/game/server/gameworld.h new file mode 100644 index 000000000..03ced1914 --- /dev/null +++ b/src/game/server/gameworld.h @@ -0,0 +1,153 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEWORLD_H +#define GAME_SERVER_GAMEWORLD_H + +#include + +class CEntity; +class CCharacter; + +/* + Class: Game World + Tracks all entities in the game. Propagates tick and + snap calls to all entities. +*/ +class CGameWorld +{ +public: + enum + { + ENTTYPE_PROJECTILE = 0, + ENTTYPE_LASER, + ENTTYPE_PICKUP, + ENTTYPE_CHARACTER, + ENTTYPE_FLAG, + NUM_ENTTYPES + }; + +private: + void Reset(); + void RemoveEntities(); + + CEntity *m_pNextTraverseEntity; + CEntity *m_apFirstEntityTypes[NUM_ENTTYPES]; + + class CGameContext *m_pGameServer; + class CConfig *m_pConfig; + class IServer *m_pServer; + +public: + class CGameContext *GameServer() { return m_pGameServer; } + class CConfig *Config() { return m_pConfig; } + class IServer *Server() { return m_pServer; } + + bool m_ResetRequested; + bool m_Paused; + CWorldCore m_Core; + + CGameWorld(); + ~CGameWorld(); + + void SetGameServer(CGameContext *pGameServer); + + CEntity *FindFirst(int Type); + + /* + Function: find_entities + Finds entities close to a position and returns them in a list. + + Arguments: + pos - Position. + radius - How close the entities have to be. + ents - Pointer to a list that should be filled with the pointers + to the entities. + max - Number of entities that fits into the ents array. + type - Type of the entities to find. + + Returns: + Number of entities found and added to the ents array. + */ + int FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type); + + /* + Function: closest_CEntity + Finds the closest CEntity of a type to a specific point. + + Arguments: + pos - The center position. + radius - How far off the CEntity is allowed to be + type - Type of the entities to find. + notthis - Entity to ignore + + Returns: + Returns a pointer to the closest CEntity or NULL if no CEntity is close enough. + */ + CEntity *ClosestEntity(vec2 Pos, float Radius, int Type, CEntity *pNotThis); + + /* + Function: interserct_CCharacter + Finds the closest CCharacter that intersects the line. + + Arguments: + pos0 - Start position + pos2 - End position + radius - How for from the line the CCharacter is allowed to be. + new_pos - Intersection position + notthis - Entity to ignore intersecting with + + Returns: + Returns a pointer to the closest hit or NULL of there is no intersection. + */ + class CCharacter *IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis = 0); + + /* + Function: insert_entity + Adds an entity to the world. + + Arguments: + entity - Entity to add + */ + void InsertEntity(CEntity *pEntity); + + /* + Function: remove_entity + Removes an entity from the world. + + Arguments: + entity - Entity to remove + */ + void RemoveEntity(CEntity *pEntity); + + /* + Function: destroy_entity + Destroys an entity in the world. + + Arguments: + entity - Entity to destroy + */ + void DestroyEntity(CEntity *pEntity); + + /* + Function: snap + Calls snap on all the entities in the world to create + the snapshot. + + Arguments: + snapping_client - ID of the client which snapshot + is being created. + */ + void Snap(int SnappingClient); + + void PostSnap(); + + /* + Function: tick + Calls tick on all the entities in the world to progress + the world to the next tick. + + */ + void Tick(); +}; + +#endif diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp new file mode 100644 index 000000000..9d2fa5a76 --- /dev/null +++ b/src/game/server/player.cpp @@ -0,0 +1,473 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "entities/character.h" +#include "entities/flag.h" +#include "gamecontext.h" +#include "gamecontroller.h" +#include "player.h" + + +MACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS) + +IServer *CPlayer::Server() const { return m_pGameServer->Server(); } + +CPlayer::CPlayer(CGameContext *pGameServer, int ClientID, bool Dummy, bool AsSpec) +{ + m_pGameServer = pGameServer; + m_RespawnTick = Server()->Tick(); + m_DieTick = Server()->Tick(); + m_ScoreStartTick = Server()->Tick(); + m_pCharacter = 0; + m_ClientID = ClientID; + m_Team = AsSpec ? TEAM_SPECTATORS : GameServer()->m_pController->GetStartTeam(); + m_SpecMode = SPEC_FREEVIEW; + m_SpectatorID = -1; + m_pSpecFlag = 0; + m_ActiveSpecSwitch = 0; + m_LastActionTick = Server()->Tick(); + m_TeamChangeTick = Server()->Tick(); + m_InactivityTickCounter = 0; + m_Dummy = Dummy; + m_IsReadyToPlay = !GameServer()->m_pController->IsPlayerReadyMode(); + m_RespawnDisabled = GameServer()->m_pController->GetStartRespawnState(); + m_DeadSpecMode = false; + m_Spawning = false; + mem_zero(&m_Latency, sizeof(m_Latency)); +} + +CPlayer::~CPlayer() +{ + delete m_pCharacter; + m_pCharacter = 0; +} + +void CPlayer::Tick() +{ + if(!IsDummy() && !Server()->ClientIngame(m_ClientID)) + return; + + Server()->SetClientScore(m_ClientID, m_Score); + + // do latency stuff + { + IServer::CClientInfo Info; + if(Server()->GetClientInfo(m_ClientID, &Info)) + { + m_Latency.m_Accum += Info.m_Latency; + m_Latency.m_AccumMax = maximum(m_Latency.m_AccumMax, Info.m_Latency); + m_Latency.m_AccumMin = minimum(m_Latency.m_AccumMin, Info.m_Latency); + } + // each second + if(Server()->Tick()%Server()->TickSpeed() == 0) + { + m_Latency.m_Avg = m_Latency.m_Accum/Server()->TickSpeed(); + m_Latency.m_Max = m_Latency.m_AccumMax; + m_Latency.m_Min = m_Latency.m_AccumMin; + m_Latency.m_Accum = 0; + m_Latency.m_AccumMin = 1000; + m_Latency.m_AccumMax = 0; + } + } + + if(m_pCharacter && !m_pCharacter->IsAlive()) + { + delete m_pCharacter; + m_pCharacter = 0; + } + + if(!GameServer()->m_pController->IsGamePaused()) + { + if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpecMode == SPEC_FREEVIEW) + m_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f)); + + if(!m_pCharacter && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick() && !m_DeadSpecMode) + Respawn(); + + if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_pSpecFlag) + { + if(m_pSpecFlag->GetCarrier()) + m_SpectatorID = m_pSpecFlag->GetCarrier()->GetPlayer()->GetCID(); + else + m_SpectatorID = -1; + } + + if(m_pCharacter) + { + if(m_pCharacter->IsAlive()) + m_ViewPos = m_pCharacter->GetPos(); + } + else if(m_Spawning && m_RespawnTick <= Server()->Tick()) + TryRespawn(); + + if(!m_DeadSpecMode && m_LastActionTick != Server()->Tick()) + ++m_InactivityTickCounter; + } + else + { + ++m_RespawnTick; + ++m_DieTick; + ++m_ScoreStartTick; + ++m_LastActionTick; + ++m_TeamChangeTick; + } +} + +void CPlayer::PostTick() +{ + // update latency value + if(m_PlayerFlags&PLAYERFLAG_SCOREBOARD) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + m_aActLatency[i] = GameServer()->m_apPlayers[i]->m_Latency.m_Min; + } + } + + // update view pos for spectators and dead players + if((m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && m_SpecMode != SPEC_FREEVIEW) + { + if(m_pSpecFlag) + m_ViewPos = m_pSpecFlag->GetPos(); + else if (GameServer()->m_apPlayers[m_SpectatorID]) + m_ViewPos = GameServer()->m_apPlayers[m_SpectatorID]->m_ViewPos; + } +} + +void CPlayer::Snap(int SnappingClient) +{ + if(!IsDummy() && !Server()->ClientIngame(m_ClientID)) + return; + + CNetObj_PlayerInfo *pPlayerInfo = static_cast(Server()->SnapNewItem(NETOBJTYPE_PLAYERINFO, m_ClientID, sizeof(CNetObj_PlayerInfo))); + if(!pPlayerInfo) + return; + + pPlayerInfo->m_PlayerFlags = m_PlayerFlags&PLAYERFLAG_CHATTING; + if(Server()->IsAuthed(m_ClientID)) + pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_ADMIN; + if(!GameServer()->m_pController->IsPlayerReadyMode() || m_IsReadyToPlay) + pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_READY; + if(m_RespawnDisabled && (!GetCharacter() || !GetCharacter()->IsAlive())) + pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_DEAD; + if(SnappingClient != -1 && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && (SnappingClient == m_SpectatorID)) + pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_WATCHING; + + pPlayerInfo->m_Latency = SnappingClient == -1 ? m_Latency.m_Min : GameServer()->m_apPlayers[SnappingClient]->m_aActLatency[m_ClientID]; + pPlayerInfo->m_Score = m_Score; + + if(m_ClientID == SnappingClient && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode)) + { + CNetObj_SpectatorInfo *pSpectatorInfo = static_cast(Server()->SnapNewItem(NETOBJTYPE_SPECTATORINFO, m_ClientID, sizeof(CNetObj_SpectatorInfo))); + if(!pSpectatorInfo) + return; + + pSpectatorInfo->m_SpecMode = m_SpecMode; + pSpectatorInfo->m_SpectatorID = m_SpectatorID; + if(m_pSpecFlag) + { + pSpectatorInfo->m_X = m_pSpecFlag->GetPos().x; + pSpectatorInfo->m_Y = m_pSpecFlag->GetPos().y; + } + else + { + pSpectatorInfo->m_X = m_ViewPos.x; + pSpectatorInfo->m_Y = m_ViewPos.y; + } + } + + // demo recording + if(SnappingClient == -1) + { + CNetObj_De_ClientInfo *pClientInfo = static_cast(Server()->SnapNewItem(NETOBJTYPE_DE_CLIENTINFO, m_ClientID, sizeof(CNetObj_De_ClientInfo))); + if(!pClientInfo) + return; + + pClientInfo->m_Local = 0; + pClientInfo->m_Team = m_Team; + StrToInts(pClientInfo->m_aName, 4, Server()->ClientName(m_ClientID)); + StrToInts(pClientInfo->m_aClan, 3, Server()->ClientClan(m_ClientID)); + pClientInfo->m_Country = Server()->ClientCountry(m_ClientID); + + for(int p = 0; p < NUM_SKINPARTS; p++) + { + StrToInts(pClientInfo->m_aaSkinPartNames[p], 6, m_TeeInfos.m_aaSkinPartNames[p]); + pClientInfo->m_aUseCustomColors[p] = m_TeeInfos.m_aUseCustomColors[p]; + pClientInfo->m_aSkinPartColors[p] = m_TeeInfos.m_aSkinPartColors[p]; + } + } +} + +void CPlayer::OnDisconnect() +{ + KillCharacter(); + + if(m_Team != TEAM_SPECTATORS) + { + // update spectator modes + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpecMode == SPEC_PLAYER && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID) + { + if(GameServer()->m_apPlayers[i]->m_DeadSpecMode) + GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); + else + { + GameServer()->m_apPlayers[i]->m_SpecMode = SPEC_FREEVIEW; + GameServer()->m_apPlayers[i]->m_SpectatorID = -1; + } + } + } + } +} + +void CPlayer::OnPredictedInput(CNetObj_PlayerInput *NewInput) +{ + // skip the input if chat is active + if((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)) + return; + + if(m_pCharacter) + m_pCharacter->OnPredictedInput(NewInput); +} + +void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) +{ + if(GameServer()->m_World.m_Paused) + { + m_PlayerFlags = NewInput->m_PlayerFlags; + return; + } + + if(NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) + { + // skip the input if chat is active + if(m_PlayerFlags&PLAYERFLAG_CHATTING) + return; + + // reset input + if(m_pCharacter) + m_pCharacter->ResetInput(); + + m_PlayerFlags = NewInput->m_PlayerFlags; + return; + } + + m_PlayerFlags = NewInput->m_PlayerFlags; + + if(m_pCharacter) + m_pCharacter->OnDirectInput(NewInput); + + if(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1)) + Respawn(); + + if(!m_pCharacter && m_Team == TEAM_SPECTATORS && (NewInput->m_Fire&1)) + { + if(!m_ActiveSpecSwitch) + { + m_ActiveSpecSwitch = true; + if(m_SpecMode == SPEC_FREEVIEW) + { + CCharacter *pChar = (CCharacter *)GameServer()->m_World.ClosestEntity(m_ViewPos, 6.0f*32, CGameWorld::ENTTYPE_CHARACTER, 0); + CFlag *pFlag = (CFlag *)GameServer()->m_World.ClosestEntity(m_ViewPos, 6.0f*32, CGameWorld::ENTTYPE_FLAG, 0); + if(pChar || pFlag) + { + if(!pChar || (pFlag && pChar && distance(m_ViewPos, pFlag->GetPos()) < distance(m_ViewPos, pChar->GetPos()))) + { + m_SpecMode = pFlag->GetTeam() == TEAM_RED ? SPEC_FLAGRED : SPEC_FLAGBLUE; + m_pSpecFlag = pFlag; + m_SpectatorID = -1; + } + else + { + m_SpecMode = SPEC_PLAYER; + m_pSpecFlag = 0; + m_SpectatorID = pChar->GetPlayer()->GetCID(); + } + } + } + else + { + m_SpecMode = SPEC_FREEVIEW; + m_pSpecFlag = 0; + m_SpectatorID = -1; + } + } + } + else if(m_ActiveSpecSwitch) + m_ActiveSpecSwitch = false; + + // check for activity + if(NewInput->m_Direction || m_LatestActivity.m_TargetX != NewInput->m_TargetX || + m_LatestActivity.m_TargetY != NewInput->m_TargetY || NewInput->m_Jump || + NewInput->m_Fire&1 || NewInput->m_Hook) + { + m_LatestActivity.m_TargetX = NewInput->m_TargetX; + m_LatestActivity.m_TargetY = NewInput->m_TargetY; + m_LastActionTick = Server()->Tick(); + m_InactivityTickCounter = 0; + } +} + +CCharacter *CPlayer::GetCharacter() +{ + if(m_pCharacter && m_pCharacter->IsAlive()) + return m_pCharacter; + return 0; +} + +void CPlayer::KillCharacter(int Weapon) +{ + if(m_pCharacter) + { + m_pCharacter->Die(m_ClientID, Weapon); + delete m_pCharacter; + m_pCharacter = 0; + } +} + +void CPlayer::Respawn() +{ + if(m_RespawnDisabled && m_Team != TEAM_SPECTATORS) + { + // enable spectate mode for dead players + m_DeadSpecMode = true; + m_IsReadyToPlay = true; + m_SpecMode = SPEC_PLAYER; + UpdateDeadSpecMode(); + return; + } + + m_DeadSpecMode = false; + + if(m_Team != TEAM_SPECTATORS) + m_Spawning = true; +} + +bool CPlayer::SetSpectatorID(int SpecMode, int SpectatorID) +{ + if((SpecMode == m_SpecMode && SpecMode != SPEC_PLAYER) || + (m_SpecMode == SPEC_PLAYER && SpecMode == SPEC_PLAYER && (SpectatorID == -1 || m_SpectatorID == SpectatorID || m_ClientID == SpectatorID))) + { + return false; + } + + if(m_Team == TEAM_SPECTATORS) + { + // check for freeview or if wanted player is playing + if(SpecMode != SPEC_PLAYER || (SpecMode == SPEC_PLAYER && GameServer()->m_apPlayers[SpectatorID] && GameServer()->m_apPlayers[SpectatorID]->GetTeam() != TEAM_SPECTATORS)) + { + if(SpecMode == SPEC_FLAGRED || SpecMode == SPEC_FLAGBLUE) + { + CFlag *pFlag = (CFlag*)GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_FLAG); + while (pFlag) + { + if ((pFlag->GetTeam() == TEAM_RED && SpecMode == SPEC_FLAGRED) || (pFlag->GetTeam() == TEAM_BLUE && SpecMode == SPEC_FLAGBLUE)) + { + m_pSpecFlag = pFlag; + if (pFlag->GetCarrier()) + m_SpectatorID = pFlag->GetCarrier()->GetPlayer()->GetCID(); + else + m_SpectatorID = -1; + break; + } + pFlag = (CFlag*)pFlag->TypeNext(); + } + if (!m_pSpecFlag) + return false; + m_SpecMode = SpecMode; + return true; + } + m_pSpecFlag = 0; + m_SpecMode = SpecMode; + m_SpectatorID = SpectatorID; + return true; + } + } + else if(m_DeadSpecMode) + { + // check if wanted player can be followed + if(SpecMode == SPEC_PLAYER && GameServer()->m_apPlayers[SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[SpectatorID])) + { + m_SpecMode = SpecMode; + m_pSpecFlag = 0; + m_SpectatorID = SpectatorID; + return true; + } + } + + return false; +} + +bool CPlayer::DeadCanFollow(CPlayer *pPlayer) const +{ + // check if wanted player is in the same team and alive + return (!pPlayer->m_RespawnDisabled || (pPlayer->GetCharacter() && pPlayer->GetCharacter()->IsAlive())) && pPlayer->GetTeam() == m_Team; +} + +void CPlayer::UpdateDeadSpecMode() +{ + // check if actual spectator id is valid + if(m_SpectatorID != -1 && GameServer()->m_apPlayers[m_SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[m_SpectatorID])) + return; + + // find player to follow + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && DeadCanFollow(GameServer()->m_apPlayers[i])) + { + m_SpectatorID = i; + return; + } + } + + // no one available to follow -> turn spectator mode off + m_DeadSpecMode = false; +} + +void CPlayer::SetTeam(int Team, bool DoChatMsg) +{ + KillCharacter(); + + m_Team = Team; + m_LastActionTick = Server()->Tick(); + m_SpecMode = SPEC_FREEVIEW; + m_SpectatorID = -1; + m_pSpecFlag = 0; + m_DeadSpecMode = false; + + // we got to wait 0.5 secs before respawning + m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; + + if(Team == TEAM_SPECTATORS) + { + // update spectator modes + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()-> m_apPlayers[i]->m_SpecMode == SPEC_PLAYER && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID) + { + if(GameServer()->m_apPlayers[i]->m_DeadSpecMode) + GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); + else + { + GameServer()->m_apPlayers[i]->m_SpecMode = SPEC_FREEVIEW; + GameServer()->m_apPlayers[i]->m_SpectatorID = -1; + } + } + } + } +} + +void CPlayer::TryRespawn() +{ + vec2 SpawnPos; + + if(!GameServer()->m_pController->CanSpawn(m_Team, &SpawnPos)) + return; + + m_Spawning = false; + m_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World); + m_pCharacter->Spawn(this, SpawnPos); + GameServer()->CreatePlayerSpawn(SpawnPos); +} diff --git a/src/game/server/player.h b/src/game/server/player.h new file mode 100644 index 000000000..a6749136d --- /dev/null +++ b/src/game/server/player.h @@ -0,0 +1,135 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_PLAYER_H +#define GAME_SERVER_PLAYER_H + +#include "alloc.h" + + +enum +{ + WEAPON_GAME = -3, // team switching etc + WEAPON_SELF = -2, // console kill command + WEAPON_WORLD = -1, // death tiles etc +}; + +// player object +class CPlayer +{ + MACRO_ALLOC_POOL_ID() + +public: + CPlayer(CGameContext *pGameServer, int ClientID, bool Dummy, bool AsSpec = false); + ~CPlayer(); + + void Init(int CID); + + void TryRespawn(); + void Respawn(); + void SetTeam(int Team, bool DoChatMsg=true); + int GetTeam() const { return m_Team; } + int GetCID() const { return m_ClientID; } + bool IsDummy() const { return m_Dummy; } + + void Tick(); + void PostTick(); + void Snap(int SnappingClient); + + void OnDirectInput(CNetObj_PlayerInput *NewInput); + void OnPredictedInput(CNetObj_PlayerInput *NewInput); + void OnDisconnect(); + + void KillCharacter(int Weapon = WEAPON_GAME); + CCharacter *GetCharacter(); + + //--------------------------------------------------------- + // this is used for snapping so we know how we can clip the view for the player + vec2 m_ViewPos; + + // states if the client is chatting, accessing a menu etc. + int m_PlayerFlags; + + // used for snapping to just update latency if the scoreboard is active + int m_aActLatency[MAX_CLIENTS]; + + // used for spectator mode + int GetSpectatorID() const { return m_SpectatorID; } + bool SetSpectatorID(int SpecMode, int SpectatorID); + bool m_DeadSpecMode; + bool DeadCanFollow(CPlayer *pPlayer) const; + void UpdateDeadSpecMode(); + + bool m_IsReadyToEnter; + bool m_IsReadyToPlay; + + bool m_RespawnDisabled; + + // + int m_Vote; + int m_VotePos; + // + int m_LastVoteCallTick; + int m_LastVoteTryTick; + int m_LastChatTeamTick; + int m_LastSetTeamTick; + int m_LastSetSpectatorModeTick; + int m_LastChangeInfoTick; + int m_LastEmoteTick; + int m_LastKillTick; + int m_LastReadyChangeTick; + + // TODO: clean this up + struct + { + char m_aaSkinPartNames[NUM_SKINPARTS][MAX_SKIN_ARRAY_SIZE]; + int m_aUseCustomColors[NUM_SKINPARTS]; + int m_aSkinPartColors[NUM_SKINPARTS]; + } m_TeeInfos; + + int m_RespawnTick; + int m_DieTick; + int m_Score; + int m_ScoreStartTick; + int m_LastActionTick; + int m_TeamChangeTick; + + int m_InactivityTickCounter; + + struct + { + int m_TargetX; + int m_TargetY; + } m_LatestActivity; + + // network latency calculations + struct + { + int m_Accum; + int m_AccumMin; + int m_AccumMax; + int m_Avg; + int m_Min; + int m_Max; + } m_Latency; + +private: + CCharacter *m_pCharacter; + CGameContext *m_pGameServer; + + CGameContext *GameServer() const { return m_pGameServer; } + IServer *Server() const; + + // + bool m_Spawning; + int m_ClientID; + int m_Team; + bool m_Dummy; + + // used for spectator mode + int m_SpecMode; + int m_SpectatorID; + class CFlag *m_pSpecFlag; + bool m_ActiveSpecSwitch; +}; + +#endif diff --git a/src/game/tuning.h b/src/game/tuning.h new file mode 100644 index 000000000..ecd7ef08d --- /dev/null +++ b/src/game/tuning.h @@ -0,0 +1,47 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_TUNING_H +#define GAME_TUNING_H +#undef GAME_TUNING_H // this file will be included several times + +// physics tuning +MACRO_TUNING_PARAM(GroundControlSpeed, ground_control_speed, 10.0f) +MACRO_TUNING_PARAM(GroundControlAccel, ground_control_accel, 100.0f / TicksPerSecond) +MACRO_TUNING_PARAM(GroundFriction, ground_friction, 0.5f) +MACRO_TUNING_PARAM(GroundJumpImpulse, ground_jump_impulse, 13.2f) +MACRO_TUNING_PARAM(AirJumpImpulse, air_jump_impulse, 12.0f) +MACRO_TUNING_PARAM(AirControlSpeed, air_control_speed, 250.0f / TicksPerSecond) +MACRO_TUNING_PARAM(AirControlAccel, air_control_accel, 1.5f) +MACRO_TUNING_PARAM(AirFriction, air_friction, 0.95f) +MACRO_TUNING_PARAM(HookLength, hook_length, 380.0f) +MACRO_TUNING_PARAM(HookFireSpeed, hook_fire_speed, 80.0f) +MACRO_TUNING_PARAM(HookDragAccel, hook_drag_accel, 3.0f) +MACRO_TUNING_PARAM(HookDragSpeed, hook_drag_speed, 15.0f) +MACRO_TUNING_PARAM(Gravity, gravity, 0.5f) + +MACRO_TUNING_PARAM(VelrampStart, velramp_start, 550) +MACRO_TUNING_PARAM(VelrampRange, velramp_range, 2000) +MACRO_TUNING_PARAM(VelrampCurvature, velramp_curvature, 1.4f) + +// weapon tuning +MACRO_TUNING_PARAM(GunCurvature, gun_curvature, 1.25f) +MACRO_TUNING_PARAM(GunSpeed, gun_speed, 2200.0f) +MACRO_TUNING_PARAM(GunLifetime, gun_lifetime, 2.0f) + +MACRO_TUNING_PARAM(ShotgunCurvature, shotgun_curvature, 1.25f) +MACRO_TUNING_PARAM(ShotgunSpeed, shotgun_speed, 2750.0f) +MACRO_TUNING_PARAM(ShotgunSpeeddiff, shotgun_speeddiff, 0.8f) +MACRO_TUNING_PARAM(ShotgunLifetime, shotgun_lifetime, 0.20f) + +MACRO_TUNING_PARAM(GrenadeCurvature, grenade_curvature, 7.0f) +MACRO_TUNING_PARAM(GrenadeSpeed, grenade_speed, 1000.0f) +MACRO_TUNING_PARAM(GrenadeLifetime, grenade_lifetime, 2.0f) + +MACRO_TUNING_PARAM(LaserReach, laser_reach, 800.0f) +MACRO_TUNING_PARAM(LaserBounceDelay, laser_bounce_delay, 150) +MACRO_TUNING_PARAM(LaserBounceNum, laser_bounce_num, 1) +MACRO_TUNING_PARAM(LaserBounceCost, laser_bounce_cost, 0) + +MACRO_TUNING_PARAM(PlayerCollision, player_collision, 1) +MACRO_TUNING_PARAM(PlayerHooking, player_hooking, 1) +#endif diff --git a/src/game/variables.h b/src/game/variables.h new file mode 100644 index 000000000..78f24f20e --- /dev/null +++ b/src/game/variables.h @@ -0,0 +1,153 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VARIABLES_H +#define GAME_VARIABLES_H +#undef GAME_VARIABLES_H // this file will be included several times + + +// client +MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use prediction for objects in the game world") +MACRO_CONFIG_INT(ClPredictPlayers, cl_predict_players, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict movements of other players") +MACRO_CONFIG_INT(ClPredictProjectiles, cl_predict_projectiles, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict position of projectiles") +MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show name plates") +MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show name plates disregarding of distance") +MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use team colors for name plates") +MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the name plates from 0 to 100%") +MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup") + +MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD") +MACRO_CONFIG_INT(ClShowChat, cl_showchat, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat") +MACRO_CONFIG_INT(ClFilterchat, cl_filterchat, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat messages from: 0=all, 1=friends only, 2=no one") +MACRO_CONFIG_INT(ClDisableWhisper, cl_disable_whisper, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable completely the whisper feature.") +MACRO_CONFIG_INT(ClShowsocial, cl_showsocial, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show social data like names, clans, chat etc.") +MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter") + +MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show double jump indicator") + +MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Warn about team balance") + +MACRO_CONFIG_INT(ClDynamicCamera, cl_dynamic_camera, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Switches camera mode. 0=static camera, 1=dynamic camera") +MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 300, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Zone that doesn't trigger the dynamic camera") +MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Trigger amount for the dynamic camera") +MACRO_CONFIG_INT(ClMouseMaxDistanceDynamic, cl_mouse_max_distance_dynamic, 1000, 1, 2000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Mouse max distance, in dynamic camera mode") +MACRO_CONFIG_INT(ClMouseMaxDistanceStatic, cl_mouse_max_distance_static, 400, 1, 2000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Mouse max distance, in static camera mode") +MACRO_CONFIG_INT(ClCameraSmoothness, cl_camera_smoothness, 0, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Camera movement speed. 0=instant, 100=slow and smooth") +MACRO_CONFIG_INT(ClCameraStabilizing, cl_camera_stabilizing, 0, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Amount of camera slowdown during cursor movement") + +MACRO_CONFIG_INT(ClCustomizeSkin, cl_customize_skin, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use a customized skin") + +MACRO_CONFIG_INT(ClShowUserId, cl_show_user_id, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show the ID for every user") + +MACRO_CONFIG_INT(EdZoomTarget, ed_zoom_target, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Zoom to the current mouse target") +MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Editor shows which keys are pressed") +MACRO_CONFIG_INT(EdColorGridInner, ed_color_grid_inner, 0xFFFFFF26, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color inner grid") +MACRO_CONFIG_INT(EdColorGridOuter, ed_color_grid_outer, 0xFF4C4C4C, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color outer grid") +MACRO_CONFIG_INT(EdColorQuadPoint, ed_color_quad_point, 0xFF0000FF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of quad points") +MACRO_CONFIG_INT(EdColorQuadPointHover, ed_color_quad_point_hover, 0xFFFFFFFF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of quad points when hovering over with the mouse cursor") +MACRO_CONFIG_INT(EdColorQuadPointActive, ed_color_quad_point_active, 0xFFFFFFFF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of active quad points") +MACRO_CONFIG_INT(EdColorQuadPivot, ed_color_quad_pivot, 0x00FF00FF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of the quad pivot") +MACRO_CONFIG_INT(EdColorQuadPivotHover, ed_color_quad_pivot_hover, 0xFFFFFFFF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of the quad pivot when hovering over with the mouse cursor") +MACRO_CONFIG_INT(EdColorQuadPivotActive, ed_color_quad_pivot_active, 0xFFFFFFFF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of the active quad pivot") +MACRO_CONFIG_INT(EdColorSelectionQuad, ed_color_selection_quad, 0xFFFFFFFF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of the selection area for a quad") +MACRO_CONFIG_INT(EdColorSelectionTile, ed_color_selection_tile, 0xFFFFFF66, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of the selection area for a tile") + +//MACRO_CONFIG_INT(ClFlow, cl_flow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") + +MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show initial set-up dialog") +MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long to show the server message of the day") +MACRO_CONFIG_INT(ClShowXmasHats, cl_show_xmas_hats, 1, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "0=never, 1=during christmas, 2=always") +MACRO_CONFIG_INT(ClShowEasterEggs, cl_show_easter_eggs, 1, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "0=never, 1=during easter, 2=always") + +MACRO_CONFIG_STR(ClVersionServer, cl_version_server, 100, "version.teeworlds.com", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to check for new versions") + +MACRO_CONFIG_STR(ClLanguagefile, cl_languagefile, 255, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "What language file to use") + +MACRO_CONFIG_INT(PlayerColorBody, player_color_body, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player body color") +MACRO_CONFIG_INT(PlayerColorMarking, player_color_marking, 0xFF0000FF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player marking color") +MACRO_CONFIG_INT(PlayerColorDecoration, player_color_decoration, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player decoration color") +MACRO_CONFIG_INT(PlayerColorHands, player_color_hands, 0x1B759E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player hands color") +MACRO_CONFIG_INT(PlayerColorFeet, player_color_feet, 0x1C873E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player feet color") +MACRO_CONFIG_INT(PlayerColorEyes, player_color_eyes, 0x0000FF, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player eyes color") +MACRO_CONFIG_INT(PlayerUseCustomColorBody, player_use_custom_color_body, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for body") +MACRO_CONFIG_INT(PlayerUseCustomColorMarking, player_use_custom_color_marking, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for marking") +MACRO_CONFIG_INT(PlayerUseCustomColorDecoration, player_use_custom_color_decoration, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for decoration") +MACRO_CONFIG_INT(PlayerUseCustomColorHands, player_use_custom_color_hands, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for hands") +MACRO_CONFIG_INT(PlayerUseCustomColorFeet, player_use_custom_color_feet, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for feet") +MACRO_CONFIG_INT(PlayerUseCustomColorEyes, player_use_custom_color_eyes, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for eyes") +MACRO_CONFIG_UTF8STR(PlayerSkin, player_skin, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin") +MACRO_CONFIG_UTF8STR(PlayerSkinBody, player_skin_body, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin body") +MACRO_CONFIG_UTF8STR(PlayerSkinMarking, player_skin_marking, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin marking") +MACRO_CONFIG_UTF8STR(PlayerSkinDecoration, player_skin_decoration, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin decoration") +MACRO_CONFIG_UTF8STR(PlayerSkinHands, player_skin_hands, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin hands") +MACRO_CONFIG_UTF8STR(PlayerSkinFeet, player_skin_feet, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin feet") +MACRO_CONFIG_UTF8STR(PlayerSkinEyes, player_skin_eyes, MAX_SKIN_ARRAY_SIZE, MAX_SKIN_LENGTH, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin eyes") + +MACRO_CONFIG_INT(UiBrowserPage, ui_browser_page, 5, 5, 8, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface serverbrowser page") +MACRO_CONFIG_INT(UiSettingsPage, ui_settings_page, 0, 0, 5, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface settings page") +MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address (Internet page)") +MACRO_CONFIG_STR(UiServerAddressLan, ui_server_address_lan, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address (LAN page)") +MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 100, 1, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor") +MACRO_CONFIG_INT(UiJoystickSens, ui_joystick_sens, 100, 1, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Joystick sensitivity for menus/editor") +MACRO_CONFIG_INT(UiAutoswitchInfotab, ui_autoswitch_infotab, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Switch to the info tab when clicking on a server") +MACRO_CONFIG_INT(UiWideview, ui_wideview, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Extended menus GUI") + +MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable clipping") + +MACRO_CONFIG_STR(ClMenuMap, cl_menu_map, 64, "auto", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background map in the menu, auto = automatic based on season") +MACRO_CONFIG_INT(ClShowMenuMap, cl_show_menu_map, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Display background map in the menu") +MACRO_CONFIG_INT(ClMenuAlpha, cl_menu_alpha, 25, 0, 75, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Transparency of the menu background") +MACRO_CONFIG_INT(ClRotationRadius, cl_rotation_radius, 30, 1, 500, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Menu camera rotation radius") +MACRO_CONFIG_INT(ClRotationSpeed, cl_rotation_speed, 40, 1, 120, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Menu camera rotations in seconds") +MACRO_CONFIG_INT(ClCameraSpeed, cl_camera_speed, 5, 1, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Menu camera speed") + +MACRO_CONFIG_INT(ClShowStartMenuImages, cl_show_start_menu_images, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show start menu images") +MACRO_CONFIG_INT(ClSkipStartMenu, cl_skip_start_menu, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Skip the start menu") + +MACRO_CONFIG_INT(ClHideSelfScore, cl_hide_self_score, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Hide player's score in the scoreboard") +MACRO_CONFIG_INT(ClStatboardInfos, cl_statboard_infos, 1259, 1, 2047, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Mask of info to display on the global statboard") +MACRO_CONFIG_INT(ClShowLocalTimeAlways, cl_show_local_time_always, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show local time") + +MACRO_CONFIG_INT(ClLastVersionPlayed, cl_last_version_played, PREV_CLIENT_VERSION, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Last version of the game that was played") + +// server +MACRO_CONFIG_INT(SvWarmup, sv_warmup, 0, -1, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Number of seconds to do warmup before match starts (0 disables, -1 all players ready)") +MACRO_CONFIG_INT(SvCountdown, sv_countdown, 0, -1, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Number of seconds to freeze the game in a countdown before match starts (0 enables only for survival gamemodes, -1 disables)") +MACRO_CONFIG_STR(SvMotd, sv_motd, 900, "", CFGFLAG_SAVE|CFGFLAG_SERVER, "Message of the day to display for the clients") +MACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Team damage") +MACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, "", CFGFLAG_SAVE|CFGFLAG_SERVER, "Maps to rotate between") +MACRO_CONFIG_INT(SvMatchesPerMap, sv_matches_per_map, 1, 1, 100, CFGFLAG_SAVE|CFGFLAG_SERVER, "Number of matches on each map before rotating") +MACRO_CONFIG_INT(SvMatchSwap, sv_match_swap, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Swap teams between matches") +MACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Allow powerups like ninja") +MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 20, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Score limit (0 disables)") +MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Time limit in minutes (0 disables)") +MACRO_CONFIG_STR(SvGametype, sv_gametype, 32, "dm", CFGFLAG_SAVE|CFGFLAG_SERVER, "Game type (dm, tdm, ctf, lms, lts)") +MACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 2, CFGFLAG_SAVE|CFGFLAG_SERVER, "Tournament mode. When enabled, players joins the server as spectator (2=additional restricted spectator chat)") +MACRO_CONFIG_INT(SvPlayerReadyMode, sv_player_ready_mode, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "When enabled, players can pause/unpause the game and start the game on warmup via their ready state") +MACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Spam protection") + +MACRO_CONFIG_INT(SvRespawnDelayTDM, sv_respawn_delay_tdm, 3, 0, 10, CFGFLAG_SAVE|CFGFLAG_SERVER, "Time needed to respawn after death in tdm gametype") + +MACRO_CONFIG_INT(SvPlayerSlots, sv_player_slots, 8, 0, MAX_PLAYERS, CFGFLAG_SAVE|CFGFLAG_SERVER, "Number of slots to reserve for players") +MACRO_CONFIG_INT(SvSkillLevel, sv_skill_level, 1, SERVERINFO_LEVEL_MIN, SERVERINFO_LEVEL_MAX, CFGFLAG_SAVE|CFGFLAG_SERVER, "Supposed player skill level") +MACRO_CONFIG_INT(SvTeambalanceTime, sv_teambalance_time, 1, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "How many minutes to wait before autobalancing teams") +MACRO_CONFIG_INT(SvInactiveKickTime, sv_inactivekick_time, 3, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "How many minutes to wait before taking care of inactive clients") +MACRO_CONFIG_INT(SvInactiveKick, sv_inactivekick, 2, 1, 3, CFGFLAG_SAVE|CFGFLAG_SERVER, "How to deal with inactive clients (1=move player to spectator, 2=move to free spectator slot/kick, 3=kick)") +MACRO_CONFIG_INT(SvInactiveKickSpec, sv_inactivekick_spec, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Kick inactive spectators") + +MACRO_CONFIG_INT(SvSilentSpectatorMode, sv_silent_spectator_mode, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Mute join/leave message of spectator") + +MACRO_CONFIG_INT(SvStrictSpectateMode, sv_strict_spectate_mode, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Restricts information in spectator mode") +MACRO_CONFIG_INT(SvVoteSpectate, sv_vote_spectate, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Allow voting to move players to spectators") +MACRO_CONFIG_INT(SvVoteSpectateRejoindelay, sv_vote_spectate_rejoindelay, 3, 0, 1000, CFGFLAG_SAVE|CFGFLAG_SERVER, "How many minutes to wait before a player can rejoin after being moved to spectators by vote") +MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_SERVER, "Allow voting to kick players") +MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SAVE|CFGFLAG_SERVER, "Minimum number of players required to start a kick vote") +MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SAVE|CFGFLAG_SERVER, "The time to ban a player if kicked by vote. 0 makes it just use kick") + +// debug +#ifdef CONF_DEBUG // this one can crash the server if not used correctly + MACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "") +#endif + +MACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(DbgTuning, dbg_tuning, 0, 0, 1, CFGFLAG_CLIENT, "") +#endif diff --git a/src/game/version.h b/src/game/version.h new file mode 100644 index 000000000..f7ea50157 --- /dev/null +++ b/src/game/version.h @@ -0,0 +1,13 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VERSION_H +#define GAME_VERSION_H +#include +#define GAME_VERSION "0.7.5" +#define GAME_NETVERSION_HASH_FORCED "802f1be60a05665f" +#define GAME_NETVERSION "0.7 " GAME_NETVERSION_HASH_FORCED +#define CLIENT_VERSION 0x0705 +#define PREV_CLIENT_VERSION 0x0704 +#define SETTINGS_FILENAME "settings07" +static const char GAME_RELEASE_VERSION[8] = "0.7.5"; +#endif diff --git a/src/game/voting.h b/src/game/voting.h new file mode 100644 index 000000000..8b006fef5 --- /dev/null +++ b/src/game/voting.h @@ -0,0 +1,37 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VOTING_H +#define GAME_VOTING_H + +enum +{ + VOTE_DESC_LENGTH=64, + VOTE_CMD_LENGTH=512, + VOTE_SEARCH_LENGTH=64, + VOTE_REASON_LENGTH=16, + + MAX_VOTE_OPTIONS=128, + MAX_VOTE_OPTION_ADD=21, + + VOTE_COOLDOWN=60, +}; + +struct CVoteOptionClient +{ + CVoteOptionClient *m_pNext; + CVoteOptionClient *m_pPrev; + char m_aDescription[VOTE_DESC_LENGTH]; + + int m_Depth; + bool m_IsSubheader; +}; + +struct CVoteOptionServer +{ + CVoteOptionServer *m_pNext; + CVoteOptionServer *m_pPrev; + char m_aDescription[VOTE_DESC_LENGTH]; + char m_aCommand[1]; +}; + +#endif diff --git a/src/mastersrv/mastersrv.cpp b/src/mastersrv/mastersrv.cpp new file mode 100644 index 000000000..e19672313 --- /dev/null +++ b/src/mastersrv/mastersrv.cpp @@ -0,0 +1,465 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "mastersrv.h" + + +enum { + MTU = 1400, + MAX_SERVERS_PER_PACKET=75, + MAX_PACKETS=16, + MAX_SERVERS=MAX_SERVERS_PER_PACKET*MAX_PACKETS, + EXPIRE_TIME = 90 +}; + +struct CCheckServer +{ + enum ServerType m_Type; + NETADDR m_Address; + NETADDR m_AltAddress; + int m_TryCount; + int64 m_TryTime; + TOKEN m_Token; +}; + +static CCheckServer m_aCheckServers[MAX_SERVERS]; +static int m_NumCheckServers = 0; + +struct CServerEntry +{ + enum ServerType m_Type; + NETADDR m_Address; + int64 m_Expire; +}; + +static CServerEntry m_aServers[MAX_SERVERS]; +static int m_NumServers = 0; + +struct CPacketData +{ + int m_Size; + struct { + unsigned char m_aHeader[sizeof(SERVERBROWSE_LIST)]; + CMastersrvAddr m_aServers[MAX_SERVERS_PER_PACKET]; + } m_Data; +}; + +CPacketData m_aPackets[MAX_PACKETS]; +static int m_NumPackets = 0; + + +struct CCountPacketData +{ + unsigned char m_Header[sizeof(SERVERBROWSE_COUNT)]; + unsigned char m_High; + unsigned char m_Low; +}; + +static CCountPacketData m_CountData; + + +CNetBan m_NetBan; + +static CNetClient m_NetChecker; // NAT/FW checker +static CNetClient m_NetOp; // main + +IConsole *m_pConsole; + +void BuildPackets() +{ + CServerEntry *pCurrent = &m_aServers[0]; + int ServersLeft = m_NumServers; + m_NumPackets = 0; + int PacketIndex = 0; + while(ServersLeft-- && m_NumPackets < MAX_PACKETS) + { + if(pCurrent->m_Type == SERVERTYPE_NORMAL) + { + if(PacketIndex % MAX_SERVERS_PER_PACKET == 0) + { + PacketIndex = 0; + m_NumPackets++; + } + + // copy header + mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)); + + // copy server addresses + if(pCurrent->m_Address.type == NETTYPE_IPV6) + { + mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, pCurrent->m_Address.ip, + sizeof(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp)); + } + else + { + static unsigned char s_aIPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}; + + mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, s_aIPV4Mapping, sizeof(s_aIPV4Mapping)); + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[12] = pCurrent->m_Address.ip[0]; + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[13] = pCurrent->m_Address.ip[1]; + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[14] = pCurrent->m_Address.ip[2]; + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[15] = pCurrent->m_Address.ip[3]; + } + + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[0] = (pCurrent->m_Address.port>>8)&0xff; + m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[1] = pCurrent->m_Address.port&0xff; + + PacketIndex++; + + m_aPackets[m_NumPackets-1].m_Size = sizeof(SERVERBROWSE_LIST) + sizeof(CMastersrvAddr)*PacketIndex; + + pCurrent++; + } + else + { + *pCurrent = m_aServers[m_NumServers-1]; + m_NumServers--; + dbg_msg("mastersrv", "error: server of invalid type, dropping it"); + } + } +} + +void SendOk(NETADDR *pAddr, TOKEN Token) +{ + CNetChunk p; + p.m_ClientID = -1; + p.m_Address = *pAddr; + p.m_Flags = NETSENDFLAG_CONNLESS; + p.m_DataSize = sizeof(SERVERBROWSE_FWOK); + p.m_pData = SERVERBROWSE_FWOK; + + // send on both to be sure + m_NetChecker.Send(&p, Token); + m_NetOp.Send(&p, Token); +} + +void SendError(NETADDR *pAddr, TOKEN Token) +{ + CNetChunk p; + p.m_ClientID = -1; + p.m_Address = *pAddr; + p.m_Flags = NETSENDFLAG_CONNLESS; + p.m_DataSize = sizeof(SERVERBROWSE_FWERROR); + p.m_pData = SERVERBROWSE_FWERROR; + m_NetOp.Send(&p, Token); +} + +void SendCheck(NETADDR *pAddr, TOKEN Token) +{ + CNetChunk p; + p.m_ClientID = -1; + p.m_Address = *pAddr; + p.m_Flags = NETSENDFLAG_CONNLESS; + p.m_DataSize = sizeof(SERVERBROWSE_FWCHECK); + p.m_pData = SERVERBROWSE_FWCHECK; + m_NetChecker.Send(&p, Token); +} + +void AddCheckserver(NETADDR *pInfo, NETADDR *pAlt, ServerType Type, TOKEN Token) +{ + // add server + if(m_NumCheckServers == MAX_SERVERS) + { + dbg_msg("mastersrv", "error: mastersrv is full"); + return; + } + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); + char aAltAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pAlt, aAltAddrStr, sizeof(aAltAddrStr), true); + dbg_msg("mastersrv", "checking: %s (%s)", aAddrStr, aAltAddrStr); + m_aCheckServers[m_NumCheckServers].m_Address = *pInfo; + m_aCheckServers[m_NumCheckServers].m_AltAddress = *pAlt; + m_aCheckServers[m_NumCheckServers].m_TryCount = 0; + m_aCheckServers[m_NumCheckServers].m_TryTime = 0; + m_aCheckServers[m_NumCheckServers].m_Type = Type; + m_aCheckServers[m_NumCheckServers].m_Token = Token; + m_NumCheckServers++; +} + +void AddServer(NETADDR *pInfo, ServerType Type) +{ + // see if server already exists in list + for(int i = 0; i < m_NumServers; i++) + { + if(net_addr_comp(&m_aServers[i].m_Address, pInfo, true) == 0) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); + dbg_msg("mastersrv", "updated: %s", aAddrStr); + m_aServers[i].m_Expire = time_get()+time_freq()*EXPIRE_TIME; + return; + } + } + + // add server + if(m_NumServers == MAX_SERVERS) + { + dbg_msg("mastersrv", "error: mastersrv is full"); + return; + } + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); + dbg_msg("mastersrv", "added: %s", aAddrStr); + m_aServers[m_NumServers].m_Address = *pInfo; + m_aServers[m_NumServers].m_Expire = time_get()+time_freq()*EXPIRE_TIME; + m_aServers[m_NumServers].m_Type = Type; + m_NumServers++; +} + +void UpdateServers() +{ + int64 Now = time_get(); + int64 Freq = time_freq(); + for(int i = 0; i < m_NumCheckServers; i++) + { + if(Now > m_aCheckServers[i].m_TryTime+Freq) + { + if(m_aCheckServers[i].m_TryCount == 10) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&m_aCheckServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true); + char aAltAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr), true); + dbg_msg("mastersrv", "check failed: %s (%s)", aAddrStr, aAltAddrStr); + + // FAIL!! + SendError(&m_aCheckServers[i].m_Address, m_aCheckServers[i].m_Token); + m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers-1]; + m_NumCheckServers--; + i--; + } + else + { + m_aCheckServers[i].m_TryCount++; + m_aCheckServers[i].m_TryTime = Now; + if(m_aCheckServers[i].m_TryCount&1) + SendCheck(&m_aCheckServers[i].m_Address, m_aCheckServers[i].m_Token); + else + SendCheck(&m_aCheckServers[i].m_AltAddress, m_aCheckServers[i].m_Token); + } + } + } +} + +void PurgeServers() +{ + int64 Now = time_get(); + int i = 0; + while(i < m_NumServers) + { + if(m_aServers[i].m_Expire < Now) + { + // remove server + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true); + dbg_msg("mastersrv", "expired: %s", aAddrStr); + m_aServers[i] = m_aServers[m_NumServers-1]; + m_NumServers--; + } + else + i++; + } +} + +void ReloadBans() +{ + m_NetBan.UnbanAll(); + m_pConsole->ExecuteFile("master.cfg"); +} + +int main(int argc, const char **argv) +{ + dbg_logger_stdout(); + cmdline_fix(&argc, &argv); + + mem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)); + + int FlagMask = CFGFLAG_MASTER; + IKernel *pKernel = IKernel::Create(); + IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv); + IConfigManager *pConfigManager = CreateConfigManager(); + CConfig *pConfig = pConfigManager->Values(); + m_pConsole = CreateConsole(FlagMask); + + bool RegisterFail = !pKernel->RegisterInterface(pStorage); + RegisterFail |= !pKernel->RegisterInterface(m_pConsole); + RegisterFail |= !pKernel->RegisterInterface(pConfigManager); + + if(RegisterFail) + return -1; + + pConfigManager->Init(FlagMask); + m_pConsole->Init(); + m_NetBan.Init(m_pConsole, pStorage); + if(argc > 1) + m_pConsole->ParseArguments(argc-1, &argv[1]); + + NETADDR BindAddr; + if(pConfig->m_Bindaddr[0] && net_host_lookup(pConfig->m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // got bindaddr + BindAddr.type = NETTYPE_ALL; + BindAddr.port = MASTERSERVER_PORT; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = MASTERSERVER_PORT; + } + + if(secure_random_init() != 0) + { + dbg_msg("mastersrv", "could not initialize secure RNG"); + return -1; + } + if(!m_NetOp.Open(BindAddr, pConfig, m_pConsole, 0, 0)) + { + dbg_msg("mastersrv", "couldn't start network (op)"); + return -1; + } + BindAddr.port = MASTERSERVER_PORT+1; + if(!m_NetChecker.Open(BindAddr, pConfig, m_pConsole, 0, 0)) + { + dbg_msg("mastersrv", "couldn't start network (checker)"); + return -1; + } + + // process pending commands + m_pConsole->StoreCommands(false); + + dbg_msg("mastersrv", "started"); + + int64 LastBuild = 0, LastBanReload = 0; + ServerType Type = SERVERTYPE_INVALID; + while(1) + { + m_NetOp.Update(); + m_NetChecker.Update(); + + // process m_aPackets + CNetChunk Packet; + TOKEN Token; + while(m_NetOp.Recv(&Packet, &Token)) + { + // check if the server is banned + if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0, 0)) + continue; + + if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT)+2 && + mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)) == 0) + { + NETADDR Alt; + unsigned char *d = (unsigned char *)Packet.m_pData; + Alt = Packet.m_Address; + Alt.port = + (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | + d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; + + // add it + AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_NORMAL, Token); + } + else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT) && + mem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT, sizeof(SERVERBROWSE_GETCOUNT)) == 0) + { + dbg_msg("mastersrv", "count requested, responding with %d", m_NumServers); + + CNetChunk p; + p.m_ClientID = -1; + p.m_Address = Packet.m_Address; + p.m_Flags = NETSENDFLAG_CONNLESS; + p.m_DataSize = sizeof(m_CountData); + p.m_pData = &m_CountData; + m_CountData.m_High = (m_NumServers>>8)&0xff; + m_CountData.m_Low = m_NumServers&0xff; + m_NetOp.Send(&p, Token); + } + else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST) && + mem_comp(Packet.m_pData, SERVERBROWSE_GETLIST, sizeof(SERVERBROWSE_GETLIST)) == 0) + { + // someone requested the list + dbg_msg("mastersrv", "requested, responding with %d servers", m_NumServers); + + CNetChunk p; + p.m_ClientID = -1; + p.m_Address = Packet.m_Address; + p.m_Flags = NETSENDFLAG_CONNLESS; + + for(int i = 0; i < m_NumPackets; i++) + { + p.m_DataSize = m_aPackets[i].m_Size; + p.m_pData = &m_aPackets[i].m_Data; + m_NetOp.Send(&p, Token); + } + } + } + + // process packets + while(m_NetChecker.Recv(&Packet, &Token)) + { + // check if the server is banned + if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0, 0)) + continue; + + if(Packet.m_DataSize == sizeof(SERVERBROWSE_FWRESPONSE) && + mem_comp(Packet.m_pData, SERVERBROWSE_FWRESPONSE, sizeof(SERVERBROWSE_FWRESPONSE)) == 0) + { + Type = SERVERTYPE_INVALID; + // remove it from checking + for(int i = 0; i < m_NumCheckServers; i++) + { + if(net_addr_comp(&m_aCheckServers[i].m_Address, &Packet.m_Address, true) == 0 || + net_addr_comp(&m_aCheckServers[i].m_AltAddress, &Packet.m_Address, true) == 0) + { + Type = m_aCheckServers[i].m_Type; + m_NumCheckServers--; + m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers]; + break; + } + } + + // drops servers that were not in the CheckServers list + if(Type == SERVERTYPE_INVALID) + continue; + + AddServer(&Packet.m_Address, Type); + SendOk(&Packet.m_Address, Token); + } + } + + if(time_get()-LastBanReload > time_freq()*300) + { + LastBanReload = time_get(); + + ReloadBans(); + } + + if(time_get()-LastBuild > time_freq()*5) + { + LastBuild = time_get(); + + PurgeServers(); + UpdateServers(); + BuildPackets(); + } + + // be nice to the CPU + thread_sleep(1); + } + + cmdline_free(argc, argv); + return 0; +} diff --git a/src/mastersrv/mastersrv.h b/src/mastersrv/mastersrv.h new file mode 100644 index 000000000..8fcd0a7ae --- /dev/null +++ b/src/mastersrv/mastersrv.h @@ -0,0 +1,35 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef MASTERSRV_MASTERSRV_H +#define MASTERSRV_MASTERSRV_H +static const int MASTERSERVER_PORT = 8283; + +enum ServerType +{ + SERVERTYPE_INVALID = -1, + SERVERTYPE_NORMAL +}; + +struct CMastersrvAddr +{ + unsigned char m_aIp[16]; + unsigned char m_aPort[2]; +}; + +static const unsigned char SERVERBROWSE_HEARTBEAT[] = {255, 255, 255, 255, 'b', 'e', 'a', '2'}; + +static const unsigned char SERVERBROWSE_GETLIST[] = {255, 255, 255, 255, 'r', 'e', 'q', '2'}; +static const unsigned char SERVERBROWSE_LIST[] = {255, 255, 255, 255, 'l', 'i', 's', '2'}; + +static const unsigned char SERVERBROWSE_GETCOUNT[] = {255, 255, 255, 255, 'c', 'o', 'u', '2'}; +static const unsigned char SERVERBROWSE_COUNT[] = {255, 255, 255, 255, 's', 'i', 'z', '2'}; + +static const unsigned char SERVERBROWSE_GETINFO[] = {255, 255, 255, 255, 'g', 'i', 'e', '3'}; +static const unsigned char SERVERBROWSE_INFO[] = {255, 255, 255, 255, 'i', 'n', 'f', '3'}; + +static const unsigned char SERVERBROWSE_FWCHECK[] = {255, 255, 255, 255, 'f', 'w', '?', '?'}; +static const unsigned char SERVERBROWSE_FWRESPONSE[] = {255, 255, 255, 255, 'f', 'w', '!', '!'}; +static const unsigned char SERVERBROWSE_FWOK[] = {255, 255, 255, 255, 'f', 'w', 'o', 'k'}; +static const unsigned char SERVERBROWSE_FWERROR[] = {255, 255, 255, 255, 'f', 'w', 'e', 'r'}; + +#endif diff --git a/src/osxlaunch/client.m b/src/osxlaunch/client.m new file mode 100644 index 000000000..cfd62570a --- /dev/null +++ b/src/osxlaunch/client.m @@ -0,0 +1,23 @@ +#import +#include + +extern int TWMain(int argc, const char **argv); + +int main(int argc, const char **argv) +{ + BOOL FinderLaunch = argc >= 2 && !str_comp_num(argv[1], "-psn", 4); + + NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; + if(!resourcePath) + return -1; + + [[NSFileManager defaultManager] changeCurrentDirectoryPath:resourcePath]; + + if(FinderLaunch) + { + const char *paArgv[2] = { argv[0], NULL }; + return TWMain(1, paArgv); + } + else + return TWMain(argc, argv); +} diff --git a/src/osxlaunch/server.m b/src/osxlaunch/server.m new file mode 100644 index 000000000..f075422ec --- /dev/null +++ b/src/osxlaunch/server.m @@ -0,0 +1,112 @@ +#import + +@interface ServerView : NSTextView +{ + NSTask *task; + NSFileHandle *file; +} +- (void)listenTo: (NSTask*)t; +@end + +@implementation ServerView +- (void)listenTo: (NSTask*)t; +{ + NSPipe *pipe; + task = t; + pipe = [NSPipe pipe]; + [task setStandardOutput: pipe]; + file = [pipe fileHandleForReading]; + + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; + + [file readInBackgroundAndNotify]; +} + +- (void) outputNotification: (NSNotification *) notification +{ + NSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain]; + NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; + NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string]; + + [[self textStorage] appendAttributedString: attrstr]; + int length = [[self textStorage] length]; + NSRange range = NSMakeRange(length, 0); + [self scrollRangeToVisible: range]; + + [attrstr release]; + [string release]; + [file readInBackgroundAndNotify]; +} + +-(void)windowWillClose:(NSNotification *)notification +{ + [task terminate]; + [NSApp terminate:self]; +} +@end + +void runServer() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSApp = [NSApplication sharedApplication]; + NSBundle* mainBundle = [NSBundle mainBundle]; + NSTask *task; + task = [[NSTask alloc] init]; + [task setCurrentDirectoryPath: [mainBundle resourcePath]]; + + // get a server config + NSOpenPanel* openDlg = [NSOpenPanel openPanel]; + [openDlg setCanChooseFiles:YES]; + + if([openDlg runModal] != NSOKButton) + return; + + NSArray* filenames = [openDlg URLs]; + if([filenames count] != 1) + return; + + NSString* filename = [filenames objectAtIndex: 0]; + NSArray* arguments = [NSArray arrayWithObjects: @"-f", filename, nil]; + + // run server + NSWindow *window; + ServerView *view; + NSRect graphicsRect; + + graphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0); + + window = [[NSWindow alloc] + initWithContentRect: graphicsRect + styleMask: NSTitledWindowMask + | NSClosableWindowMask + | NSMiniaturizableWindowMask + backing: NSBackingStoreBuffered + defer: NO]; + + [window setTitle: @"Teeworlds Server"]; + + view = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease]; + [view setEditable: NO]; + [view setRulerVisible: YES]; + + [window setContentView: view]; + [window setDelegate: view]; + [window makeKeyAndOrderFront: nil]; + + [view listenTo: task]; + [task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @"teeworlds_srv"]]; + [task setArguments: arguments]; + [task launch]; + [NSApp run]; + [task terminate]; + + [NSApp release]; + [pool release]; +} + +int main (int argc, char **argv) +{ + runServer(); + + return 0; +} diff --git a/src/osxlaunch/server.mm b/src/osxlaunch/server.mm new file mode 100644 index 000000000..3135d439c --- /dev/null +++ b/src/osxlaunch/server.mm @@ -0,0 +1,108 @@ +#import + +@interface ServerView : NSTextView +{ + NSTask *task; + NSFileHandle *file; +} +- (void)listenTo: (NSTask *)t; +@end + +@implementation ServerView +- (void)listenTo: (NSTask *)t +{ + NSPipe *pipe; + task = t; + pipe = [NSPipe pipe]; + [task setStandardOutput: pipe]; + file = [pipe fileHandleForReading]; + + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; + + [file readInBackgroundAndNotify]; +} + +- (void) outputNotification: (NSNotification *) notification +{ + NSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain]; + NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; + NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string]; + + [[self textStorage] appendAttributedString: attrstr]; + int length = [[self textStorage] length]; + NSRange range = NSMakeRange(length, 0); + [self scrollRangeToVisible: range]; + + [attrstr release]; + [string release]; + [file readInBackgroundAndNotify]; +} + +-(void)windowWillClose:(NSNotification *)notification +{ + [task terminate]; + [NSApp terminate:self]; +} +@end + +void runServer() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSApp = [NSApplication sharedApplication]; + NSBundle *mainBundle = [NSBundle mainBundle]; + NSTask *task; + task = [[NSTask alloc] init]; + [task setCurrentDirectoryPath: [mainBundle resourcePath]]; + + // get a server config + NSOpenPanel *openDlg = [NSOpenPanel openPanel]; + [openDlg setCanChooseFiles:YES]; + + if([openDlg runModal] != NSOKButton) + return; + + NSString *filename = [[openDlg URL] path]; + NSArray *arguments = [NSArray arrayWithObjects: @"-f", filename, nil]; + + // run server + NSWindow *window; + ServerView *view; + NSRect graphicsRect; + + graphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0); + + window = [[NSWindow alloc] + initWithContentRect: graphicsRect + styleMask: NSTitledWindowMask + | NSClosableWindowMask + | NSMiniaturizableWindowMask + backing: NSBackingStoreBuffered + defer: NO]; + + [window setTitle: @"Teeworlds Server"]; + + view = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease]; + [view setEditable: NO]; + [view setRulerVisible: YES]; + + [window setContentView: view]; + [window setDelegate: (id)view]; + [window makeKeyAndOrderFront: nil]; + + [view listenTo: task]; + [task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @"teeworlds_srv"]]; + [task setArguments: arguments]; + [task launch]; + [NSApp run]; + [task terminate]; + + [NSApp release]; + [pool release]; +} + +int main(int argc, char **argv) +{ + runServer(); + + return 0; +} diff --git a/src/test/bytes_be.cpp b/src/test/bytes_be.cpp new file mode 100644 index 000000000..5879b17eb --- /dev/null +++ b/src/test/bytes_be.cpp @@ -0,0 +1,33 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" + +#include + +#include + +static const int INT_DATA[] = {0, 1, -1, 32, 64, 256, -512, 12345, -123456, 1234567, 12345678, 123456789, 2147483647, (-2147483647 - 1)}; +static const int INT_NUM = sizeof(INT_DATA) / sizeof(int); + +static const unsigned UINT_DATA[] = {0u, 1u, 2u, 32u, 64u, 256u, 512u, 12345u, 123456u, 1234567u, 12345678u, 123456789u, 2147483647u, 2147483648u, 4294967295u}; +static const int UINT_NUM = sizeof(INT_DATA) / sizeof(unsigned); + +TEST(BytePacking, RoundtripInt) +{ + for(int i = 0; i < INT_NUM; i++) + { + unsigned char aPacked[4]; + int_to_bytes_be(aPacked, INT_DATA[i]); + EXPECT_EQ(bytes_be_to_int(aPacked), INT_DATA[i]); + } +} + +TEST(BytePacking, RoundtripUnsigned) +{ + for(int i = 0; i < UINT_NUM; i++) + { + unsigned char aPacked[4]; + uint_to_bytes_be(aPacked, UINT_DATA[i]); + EXPECT_EQ(bytes_be_to_uint(aPacked), UINT_DATA[i]); + } +} diff --git a/src/test/compression.cpp b/src/test/compression.cpp new file mode 100644 index 000000000..89f5b46b8 --- /dev/null +++ b/src/test/compression.cpp @@ -0,0 +1,70 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +static const int DATA[] = {0, 1, -1, 32, 64, 256, -512, 12345, -123456, 1234567, 12345678, 123456789, 2147483647, (-2147483647 - 1)}; +static const int NUM = sizeof(DATA) / sizeof(int); +static const int SIZES[NUM] = {1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5}; + +TEST(CVariableInt, RoundtripPackUnpack) +{ + for(int i = 0; i < NUM; i++) + { + unsigned char aPacked[CVariableInt::MAX_BYTES_PACKED]; + int Result; + EXPECT_EQ(int(CVariableInt::Pack(aPacked, DATA[i]) - aPacked), SIZES[i]); + EXPECT_EQ(int(CVariableInt::Unpack(aPacked, &Result) - aPacked), SIZES[i]); + EXPECT_EQ(Result, DATA[i]); + } +} + +TEST(CVariableInt, UnpackInvalid) +{ + unsigned char aPacked[CVariableInt::MAX_BYTES_PACKED]; + for(int i = 0; i < CVariableInt::MAX_BYTES_PACKED; i++) + aPacked[i] = 0xFF; + + int Result; + EXPECT_EQ(int(CVariableInt::Unpack(aPacked, &Result) - aPacked), int(CVariableInt::MAX_BYTES_PACKED)); + EXPECT_EQ(Result, (-2147483647 - 1)); + + aPacked[0] &= ~0x40; // unset sign bit + + EXPECT_EQ(int(CVariableInt::Unpack(aPacked, &Result) - aPacked), int(CVariableInt::MAX_BYTES_PACKED)); + EXPECT_EQ(Result, 2147483647); +} + +TEST(CVariableInt, RoundtripCompressDecompress) +{ + unsigned char aCompressed[NUM * CVariableInt::MAX_BYTES_PACKED]; + int aDecompressed[NUM]; + long ExpectedCompressedSize = 0; + for(int i = 0; i < NUM; i++) + ExpectedCompressedSize += SIZES[i]; + + long CompressedSize = CVariableInt::Compress(DATA, sizeof(DATA), aCompressed, sizeof(aCompressed)); + ASSERT_EQ(CompressedSize, ExpectedCompressedSize); + long DecompressedSize = CVariableInt::Decompress(aCompressed, ExpectedCompressedSize, aDecompressed, sizeof(aDecompressed)); + ASSERT_EQ(DecompressedSize, sizeof(DATA)); + for(int i = 0; i < NUM; i++) + { + EXPECT_EQ(aDecompressed[i], DATA[i]); + } +} + +TEST(CVariableInt, CompressBufferTooSmall) +{ + unsigned char aCompressed[NUM]; // too small + long CompressedSize = CVariableInt::Compress(DATA, sizeof(DATA), aCompressed, sizeof(aCompressed)); + ASSERT_EQ(CompressedSize, -1); +} + +TEST(CVariableInt, DecompressBufferTooSmall) +{ + unsigned char aCompressed[] = {0x00, 0x01, 0x40, 0x20, 0x80, 0x01, 0x80, 0x04, 0xFF, 0x07, 0xB9, 0xC0, 0x01}; + int aUncompressed[4]; // too small + long CompressedSize = CVariableInt::Decompress(aCompressed, sizeof(aCompressed), aUncompressed, sizeof(aUncompressed)); + ASSERT_EQ(CompressedSize, -1); +} diff --git a/src/test/datafile.cpp b/src/test/datafile.cpp new file mode 100644 index 000000000..9ca6b924e --- /dev/null +++ b/src/test/datafile.cpp @@ -0,0 +1,67 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" + +#include + +#include +#include + +TEST(Datafile, RoundtripItemDataAndSize) +{ + CTestInfo Info; + char aFilename[64]; + Info.Filename(aFilename, sizeof(aFilename), ".datafile"); + IStorage *pStorage = CreateTestStorage(); + CDataFileWriter Writer; + ASSERT_TRUE(Writer.Open(pStorage, aFilename)); + + static const char TEST_DATA[] = "Hello World!"; + int Index = Writer.AddData(sizeof(TEST_DATA), TEST_DATA); + int Index4 = Writer.AddData(4, TEST_DATA); + int aItem[2] = {Index, Index4}; + Writer.AddItem(12, 34, sizeof(aItem), aItem); + EXPECT_TRUE(Writer.Finish()); + + CDataFileReader Reader; + EXPECT_FALSE(Reader.IsOpen()); + ASSERT_TRUE(Reader.Open(pStorage, aFilename, IStorage::TYPE_ALL)); + EXPECT_TRUE(Reader.IsOpen()); + + ASSERT_EQ(Reader.GetDataSize(Index), sizeof(TEST_DATA)); + EXPECT_TRUE(mem_comp(Reader.GetData(Index), TEST_DATA, sizeof(TEST_DATA)) == 0); + ASSERT_EQ(Reader.GetDataSize(Index4), 4); + EXPECT_TRUE(mem_comp(Reader.GetData(Index), TEST_DATA, 4) == 0); + + static const char REPL_DATA[] = "Replacement"; + char *pReplace4 = (char *)mem_alloc(4); + mem_copy(pReplace4, REPL_DATA, 4); + char *pReplace = (char *)mem_alloc(sizeof(REPL_DATA)); + mem_copy(pReplace, REPL_DATA, sizeof(REPL_DATA)); + Reader.ReplaceData(Index, pReplace4, 4); + Reader.ReplaceData(Index4, pReplace, sizeof(REPL_DATA)); + + ASSERT_EQ(Reader.GetDataSize(Index), 4); + EXPECT_TRUE(mem_comp(Reader.GetData(Index), REPL_DATA, 4) == 0); + ASSERT_EQ(Reader.GetDataSize(Index4), sizeof(REPL_DATA)); + EXPECT_TRUE(mem_comp(Reader.GetData(Index4), REPL_DATA, sizeof(REPL_DATA)) == 0); + + bool FoundItem = false; + for(int i = 0; i < Reader.NumItems(); i++) + { + int Type; + int ID; + void *pItem = Reader.GetItem(i, &Type, &ID); + ASSERT_EQ(Reader.GetItemSize(i), sizeof(aItem)); + EXPECT_TRUE(mem_comp(pItem, aItem, sizeof(aItem)) == 0); + EXPECT_EQ(Type, 12); + EXPECT_EQ(ID, 34); + + FoundItem = true; + } + EXPECT_TRUE(FoundItem); + + EXPECT_TRUE(Reader.Close()); + + EXPECT_TRUE(pStorage->RemoveFile(aFilename, IStorage::TYPE_SAVE)); +} diff --git a/src/test/fs.cpp b/src/test/fs.cpp new file mode 100644 index 000000000..2d14ef53c --- /dev/null +++ b/src/test/fs.cpp @@ -0,0 +1,16 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" +#include + +#include + +TEST(Filesystem, CreateCloseDelete) +{ + CTestInfo Info; + + IOHANDLE File = io_open(Info.m_aFilename, IOFLAG_WRITE); + ASSERT_TRUE(File); + EXPECT_FALSE(io_close(File)); + EXPECT_FALSE(fs_remove(Info.m_aFilename)); +} diff --git a/src/test/git_revision.cpp b/src/test/git_revision.cpp new file mode 100644 index 000000000..49b5411bc --- /dev/null +++ b/src/test/git_revision.cpp @@ -0,0 +1,16 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include + +extern const char *GIT_SHORTREV_HASH; + +TEST(GitRevision, ExistsOrNull) +{ + if(GIT_SHORTREV_HASH) + { + ASSERT_STRNE(GIT_SHORTREV_HASH, ""); + } +} diff --git a/src/test/hash.cpp b/src/test/hash.cpp new file mode 100644 index 000000000..8e156ae6d --- /dev/null +++ b/src/test/hash.cpp @@ -0,0 +1,44 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include +#include + +static void Expect(SHA256_DIGEST Actual, const char *pWanted) +{ + char aActual[SHA256_MAXSTRSIZE]; + sha256_str(Actual, aActual, sizeof(aActual)); + EXPECT_STREQ(aActual, pWanted); +} + +TEST(Hash, Sha256) +{ + // https://en.wikipedia.org/w/index.php?title=SHA-2&oldid=840187620#Test_vectors + Expect(sha256("", 0), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + SHA256_CTX ctxt; + + sha256_init(&ctxt); + Expect(sha256_finish(&ctxt), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + + // printf 'The quick brown fox jumps over the lazy dog.' | sha256sum + char QUICK_BROWN_FOX[] = "The quick brown fox jumps over the lazy dog."; + Expect(sha256(QUICK_BROWN_FOX, str_length(QUICK_BROWN_FOX)), "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"); + + sha256_init(&ctxt); + sha256_update(&ctxt, "The ", 4); + sha256_update(&ctxt, "quick ", 6); + sha256_update(&ctxt, "brown ", 6); + sha256_update(&ctxt, "fox ", 4); + sha256_update(&ctxt, "jumps ", 6); + sha256_update(&ctxt, "over ", 5); + sha256_update(&ctxt, "the ", 4); + sha256_update(&ctxt, "lazy ", 5); + sha256_update(&ctxt, "dog.", 4); + Expect(sha256_finish(&ctxt), "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"); +} + +TEST(Hash, Sha256Eq) +{ + EXPECT_EQ(sha256("", 0), sha256("", 0)); +} diff --git a/src/test/io.cpp b/src/test/io.cpp new file mode 100644 index 000000000..536391bcb --- /dev/null +++ b/src/test/io.cpp @@ -0,0 +1,65 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" +#include + +#include + +void TestFileRead(const char *pWritten, bool SkipBom, const char *pRead) +{ + CTestInfo Info; + char aBuf[512] = {0}; + IOHANDLE File = io_open(Info.m_aFilename, IOFLAG_WRITE); + ASSERT_TRUE(File); + EXPECT_EQ(io_write(File, pWritten, str_length(pWritten)), str_length(pWritten)); + EXPECT_FALSE(io_close(File)); + File = io_open(Info.m_aFilename, IOFLAG_READ | (SkipBom ? IOFLAG_SKIP_BOM : 0)); + ASSERT_TRUE(File); + EXPECT_EQ(io_read(File, aBuf, sizeof(aBuf)), str_length(pRead)); + EXPECT_TRUE(mem_comp(aBuf, pRead, str_length(pRead)) == 0); + EXPECT_FALSE(io_close(File)); + + fs_remove(Info.m_aFilename); +} + +TEST(Io, Read1) +{ + TestFileRead("", false, ""); +} +TEST(Io, Read2) +{ + TestFileRead("abc", false, "abc"); +} +TEST(Io, Read3) +{ + TestFileRead("\xef\xbb\xbf", false, "\xef\xbb\xbf"); +} +TEST(Io, Read4) +{ + TestFileRead("\xef\xbb\xbfxyz", false, "\xef\xbb\xbfxyz"); +} + +TEST(Io, ReadBom1) +{ + TestFileRead("", true, ""); +} +TEST(Io, ReadBom2) +{ + TestFileRead("abc", true, "abc"); +} +TEST(Io, ReadBom3) +{ + TestFileRead("\xef\xbb\xbf", true, ""); +} +TEST(Io, ReadBom4) +{ + TestFileRead("\xef\xbb\xbfxyz", true, "xyz"); +} +TEST(Io, ReadBom5) +{ + TestFileRead("\xef\xbb\xbf\xef\xbb\xbf", true, "\xef\xbb\xbf"); +} +TEST(Io, ReadBom6) +{ + TestFileRead("\xef\xbb\xbfxyz\xef\xbb\xbf", true, "xyz\xef\xbb\xbf"); +} diff --git a/src/test/jsonwriter.cpp b/src/test/jsonwriter.cpp new file mode 100644 index 000000000..5196878df --- /dev/null +++ b/src/test/jsonwriter.cpp @@ -0,0 +1,112 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" +#include + +#include +#include + +#if defined(CONF_FAMILY_WINDOWS) + #define LINE_ENDING "\r\n" +#else + #define LINE_ENDING "\n" +#endif + +class JsonWriter : public ::testing::Test +{ +protected: + CTestInfo m_Info; + CJsonWriter *m_pJson; + char m_aOutputFilename[64]; + + JsonWriter() + : m_pJson(0) + { + m_Info.Filename(m_aOutputFilename, sizeof(m_aOutputFilename), + "-got.json"); + IOHANDLE File = io_open(m_aOutputFilename, IOFLAG_WRITE); + EXPECT_TRUE(File); + m_pJson = new CJsonWriter(File); + } + + void Expect(const char *pExpected) + { + ASSERT_TRUE(m_pJson); + delete m_pJson; + m_pJson = 0; + + char *pOutput = fs_read_str(m_aOutputFilename); + ASSERT_TRUE(pOutput); + EXPECT_STREQ(pOutput, pExpected); + bool Correct = str_comp(pOutput, pExpected) == 0; + mem_free(pOutput); + + if(!Correct) + { + char aFilename[64]; + m_Info.Filename(aFilename, sizeof(aFilename), + "-expected.json"); + IOHANDLE File = io_open(aFilename, IOFLAG_WRITE); + ASSERT_TRUE(File); + io_write(File, pExpected, str_length(pExpected)); + io_close(File); + } + else + { + fs_remove(m_aOutputFilename); + } + } +}; + +TEST_F(JsonWriter, EmptyObject) +{ + m_pJson->BeginObject(); + m_pJson->EndObject(); + Expect("{" LINE_ENDING "}" LINE_ENDING); +} + +TEST_F(JsonWriter, EmptyArray) +{ + m_pJson->BeginArray(); + m_pJson->EndArray(); + Expect("[" LINE_ENDING "]" LINE_ENDING); +} + +TEST_F(JsonWriter, SpecialCharacters) +{ + m_pJson->BeginObject(); + m_pJson->WriteAttribute("\x01\"'\r\n\t"); + m_pJson->BeginArray(); + m_pJson->WriteStrValue(" \"'abc\x01\n"); + m_pJson->EndArray(); + m_pJson->EndObject(); + Expect( + "{" LINE_ENDING + "\t\"\\u0001\\\"'\\r\\n\\t\": [" LINE_ENDING + "\t\t\" \\\"'abc\\u0001\\n\"" LINE_ENDING + "\t]" LINE_ENDING + "}" LINE_ENDING + ); +} + +TEST_F(JsonWriter, HelloWorld) +{ + m_pJson->WriteStrValue("hello world"); + Expect("\"hello world\"" LINE_ENDING); +} + +TEST_F(JsonWriter, Unicode) +{ + m_pJson->WriteStrValue("Heizölrückstoßabdämpfung"); + Expect("\"Heizölrückstoßabdämpfung\"" LINE_ENDING); +} + +TEST_F(JsonWriter, True) { m_pJson->WriteBoolValue(true); Expect("true" LINE_ENDING); } +TEST_F(JsonWriter, False) { m_pJson->WriteBoolValue(false); Expect("false" LINE_ENDING); } +TEST_F(JsonWriter, Null) { m_pJson->WriteNullValue(); Expect("null" LINE_ENDING); } +TEST_F(JsonWriter, EmptyString) { m_pJson->WriteStrValue(""); Expect("\"\"" LINE_ENDING); } +TEST_F(JsonWriter, Zero) { m_pJson->WriteIntValue(0); Expect("0" LINE_ENDING); } +TEST_F(JsonWriter, One) { m_pJson->WriteIntValue(1); Expect("1" LINE_ENDING); } +TEST_F(JsonWriter, MinusOne) { m_pJson->WriteIntValue(-1); Expect("-1" LINE_ENDING); } +TEST_F(JsonWriter, Large) { m_pJson->WriteIntValue(INT_MAX); Expect("2147483647" LINE_ENDING); } +TEST_F(JsonWriter, Small) { m_pJson->WriteIntValue(INT_MIN); Expect("-2147483648" LINE_ENDING); } diff --git a/src/test/sorted_array.cpp b/src/test/sorted_array.cpp new file mode 100644 index 000000000..25004abe3 --- /dev/null +++ b/src/test/sorted_array.cpp @@ -0,0 +1,11 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +TEST(SortedArray, SortEmptyRange) +{ + sorted_array x; + x.sort_range(); +} diff --git a/src/test/storage.cpp b/src/test/storage.cpp new file mode 100644 index 000000000..995c8df78 --- /dev/null +++ b/src/test/storage.cpp @@ -0,0 +1,45 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" + +#include + +#include + +TEST(Storage, FindFile) +{ + CTestInfo Info; + char aFilenameWithDot[128]; + str_format(aFilenameWithDot, sizeof(aFilenameWithDot), "./%s", Info.m_aFilename); + + IStorage *pStorage = CreateTestStorage(); + IOHANDLE File = pStorage->OpenFile(Info.m_aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + ASSERT_TRUE(File); + EXPECT_EQ(io_write(File, "test\n", 5), 5); + EXPECT_FALSE(io_close(File)); + + SHA256_DIGEST Sha256 = sha256("test\n", 5); + SHA256_DIGEST WrongSha256 = sha256("", 0); + + char aFound[128]; + + EXPECT_TRUE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound))); + EXPECT_STREQ(aFound, aFilenameWithDot); + + EXPECT_TRUE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0x3bb935c6, 5)); + EXPECT_STREQ(aFound, aFilenameWithDot); + + EXPECT_TRUE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), &Sha256, 0x3bb935c6, 5)); + EXPECT_STREQ(aFound, aFilenameWithDot); + + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0, 0)); + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0x3bb935c6, 0)); + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0, 5)); + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0x3bb935c5, 5)); + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), 0, 0x3bb935c6, 6)); + + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), &WrongSha256, 0x3bb935c6, 5)); + EXPECT_FALSE(pStorage->FindFile(Info.m_aFilename, ".", IStorage::TYPE_ALL, aFound, sizeof(aFound), &SHA256_ZEROED, 0x3bb935c6, 5)); + + EXPECT_TRUE(pStorage->RemoveFile(Info.m_aFilename, IStorage::TYPE_SAVE)); +} diff --git a/src/test/str.cpp b/src/test/str.cpp new file mode 100644 index 000000000..9d0f9b374 --- /dev/null +++ b/src/test/str.cpp @@ -0,0 +1,165 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +TEST(Str, Startswith) +{ + EXPECT_TRUE(str_startswith("abcdef", "abc")); + EXPECT_FALSE(str_startswith("abc", "abcdef")); + + EXPECT_TRUE(str_startswith("xyz", "")); + EXPECT_FALSE(str_startswith("", "xyz")); + + EXPECT_FALSE(str_startswith("house", "home")); + EXPECT_FALSE(str_startswith("blackboard", "board")); + + EXPECT_TRUE(str_startswith("поплавать", "по")); + EXPECT_FALSE(str_startswith("плавать", "по")); + + static const char ABCDEFG[] = "abcdefg"; + static const char ABC[] = "abc"; + EXPECT_EQ(str_startswith(ABCDEFG, ABC) - ABCDEFG, str_length(ABC)); +} + +TEST(Str, StartswithNocase) +{ + EXPECT_TRUE(str_startswith_nocase("Abcdef", "abc")); + EXPECT_FALSE(str_startswith_nocase("aBc", "abcdef")); + + EXPECT_TRUE(str_startswith_nocase("xYz", "")); + EXPECT_FALSE(str_startswith_nocase("", "xYz")); + + EXPECT_FALSE(str_startswith_nocase("house", "home")); + EXPECT_FALSE(str_startswith_nocase("Blackboard", "board")); + + EXPECT_TRUE(str_startswith_nocase("поплавать", "по")); + EXPECT_FALSE(str_startswith_nocase("плавать", "по")); + + static const char ABCDEFG[] = "aBcdefg"; + static const char ABC[] = "abc"; + EXPECT_EQ(str_startswith_nocase(ABCDEFG, ABC) - ABCDEFG, str_length(ABC)); +} + +TEST(Str, Endswith) +{ + EXPECT_TRUE(str_endswith("abcdef", "def")); + EXPECT_FALSE(str_endswith("def", "abcdef")); + + EXPECT_TRUE(str_endswith("xyz", "")); + EXPECT_FALSE(str_endswith("", "xyz")); + + EXPECT_FALSE(str_endswith("rhyme", "mine")); + EXPECT_FALSE(str_endswith("blackboard", "black")); + + EXPECT_TRUE(str_endswith("люди", "юди")); + EXPECT_FALSE(str_endswith("люди", "любовь")); + + static const char ABCDEFG[] = "abcdefg"; + static const char DEFG[] = "defg"; + EXPECT_EQ(str_endswith(ABCDEFG, DEFG) - ABCDEFG, + str_length(ABCDEFG) - str_length(DEFG)); +} + +TEST(Str, EndswithNocase) +{ + EXPECT_TRUE(str_endswith_nocase("abcdef", "deF")); + EXPECT_FALSE(str_endswith_nocase("def", "abcdef")); + + EXPECT_TRUE(str_endswith_nocase("xyz", "")); + EXPECT_FALSE(str_endswith_nocase("", "xyz")); + + EXPECT_FALSE(str_endswith_nocase("rhyme", "minE")); + EXPECT_FALSE(str_endswith_nocase("blackboard", "black")); + + EXPECT_TRUE(str_endswith_nocase("люди", "юди")); + EXPECT_FALSE(str_endswith_nocase("люди", "любовь")); + + static const char ABCDEFG[] = "abcdefG"; + static const char DEFG[] = "defg"; + EXPECT_EQ(str_endswith_nocase(ABCDEFG, DEFG) - ABCDEFG, + str_length(ABCDEFG) - str_length(DEFG)); +} + +TEST(StrFormat, Positional) +{ + char aBuf[256]; + + // normal + str_format(aBuf, sizeof(aBuf), "%s %s", "first", "second"); + EXPECT_STREQ(aBuf, "first second"); + + // normal with positional arguments + str_format(aBuf, sizeof(aBuf), "%1$s %2$s", "first", "second"); + EXPECT_STREQ(aBuf, "first second"); + + // reverse + str_format(aBuf, sizeof(aBuf), "%2$s %1$s", "first", "second"); + EXPECT_STREQ(aBuf, "second first"); + + // duplicate + str_format(aBuf, sizeof(aBuf), "%1$s %1$s %2$d %1$s %2$d", "str", 1); + EXPECT_STREQ(aBuf, "str str 1 str 1"); +} + +TEST(Str, PathUnsafe) +{ + EXPECT_TRUE(str_path_unsafe("..")); + EXPECT_TRUE(str_path_unsafe("/..")); + EXPECT_TRUE(str_path_unsafe("/../")); + EXPECT_TRUE(str_path_unsafe("../")); + + EXPECT_TRUE(str_path_unsafe("/../foobar")); + EXPECT_TRUE(str_path_unsafe("../foobar")); + EXPECT_TRUE(str_path_unsafe("foobar/../foobar")); + EXPECT_TRUE(str_path_unsafe("foobar/..")); + EXPECT_TRUE(str_path_unsafe("foobar/../")); + + EXPECT_FALSE(str_path_unsafe("abc")); + EXPECT_FALSE(str_path_unsafe("abc/")); + EXPECT_FALSE(str_path_unsafe("abc/def")); + EXPECT_FALSE(str_path_unsafe("abc/def.txt")); + EXPECT_FALSE(str_path_unsafe("abc\\")); + EXPECT_FALSE(str_path_unsafe("abc\\def")); + EXPECT_FALSE(str_path_unsafe("abc\\def.txt")); + EXPECT_FALSE(str_path_unsafe("abc/def\\ghi.txt")); + EXPECT_FALSE(str_path_unsafe("любовь")); +} + +TEST(Str, Utf8Stats) +{ + int Size, Count; + + str_utf8_stats("abc", 4, 3, &Size, &Count); + EXPECT_EQ(Size, 3); + EXPECT_EQ(Count, 3); + + str_utf8_stats("abc", 2, 3, &Size, &Count); + EXPECT_EQ(Size, 1); + EXPECT_EQ(Count, 1); + + str_utf8_stats("", 1, 0, &Size, &Count); + EXPECT_EQ(Size, 0); + EXPECT_EQ(Count, 0); + + str_utf8_stats("abcde", 6, 5, &Size, &Count); + EXPECT_EQ(Size, 5); + EXPECT_EQ(Count, 5); + + str_utf8_stats("любовь", 13, 6, &Size, &Count); + EXPECT_EQ(Size, 12); + EXPECT_EQ(Count, 6); + + str_utf8_stats("abc愛", 7, 4, &Size, &Count); + EXPECT_EQ(Size, 6); + EXPECT_EQ(Count, 4); + + str_utf8_stats("abc愛", 6, 4, &Size, &Count); + EXPECT_EQ(Size, 3); + EXPECT_EQ(Count, 3); + + str_utf8_stats("любовь", 13, 3, &Size, &Count); + EXPECT_EQ(Size, 6); + EXPECT_EQ(Count, 3); +} diff --git a/src/test/test.cpp b/src/test/test.cpp new file mode 100644 index 000000000..140b5cb39 --- /dev/null +++ b/src/test/test.cpp @@ -0,0 +1,31 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "test.h" +#include + +#include + +CTestInfo::CTestInfo() +{ + const ::testing::TestInfo *pTestInfo = + ::testing::UnitTest::GetInstance()->current_test_info(); + str_format(m_aFilenamePrefix, sizeof(m_aFilenamePrefix), "%s.%s-%d", + pTestInfo->test_case_name(), pTestInfo->name(), pid()); + Filename(m_aFilename, sizeof(m_aFilename), ".tmp"); +} + +void CTestInfo::Filename(char *pBuffer, int BufferLength, const char *pSuffix) +{ + str_format(pBuffer, BufferLength, "%s%s", m_aFilenamePrefix, pSuffix); +} + +int main(int argc, const char **argv) +{ + cmdline_fix(&argc, &argv); + ::testing::InitGoogleTest(&argc, const_cast(argv)); + net_init(); + int Result = RUN_ALL_TESTS(); + secure_random_uninit(); + cmdline_free(argc, argv); + return Result; +} diff --git a/src/test/test.h b/src/test/test.h new file mode 100644 index 000000000..de15c4de7 --- /dev/null +++ b/src/test/test.h @@ -0,0 +1,13 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef TEST_TEST_H +#define TEST_TEST_H +class CTestInfo +{ +public: + CTestInfo(); + void Filename(char *pBuffer, int BufferLength, const char *pSuffix); + char m_aFilenamePrefix[64]; + char m_aFilename[64]; +}; +#endif // TEST_TEST_H diff --git a/src/test/thread.cpp b/src/test/thread.cpp new file mode 100644 index 000000000..8142a9cce --- /dev/null +++ b/src/test/thread.cpp @@ -0,0 +1,52 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include + +#include + +static void Nothing(void *pUser) +{ + (void)pUser; +} + +TEST(Thread, Detach) +{ + void *pThread = thread_init(Nothing, 0); + thread_detach(pThread); +} + +static void SetToOne(void *pUser) +{ + *(int *)pUser = 1; +} + +TEST(Thread, Wait) +{ + int Integer = 0; + void *pThread = thread_init(SetToOne, &Integer); + thread_wait(pThread); + EXPECT_EQ(Integer, 1); + thread_destroy(pThread); +} + +TEST(Thread, Yield) +{ + thread_yield(); +} + +static void LockThread(void *pUser) +{ + LOCK *pLock = (LOCK *)pUser; + lock_wait(*pLock); + lock_unlock(*pLock); +} + +TEST(Thread, Lock) +{ + LOCK Lock = lock_create(); + lock_wait(Lock); + void *pThread = thread_init(LockThread, &Lock); + lock_unlock(Lock); + thread_wait(pThread); + thread_destroy(pThread); +} diff --git a/src/versionsrv/mapversions.h b/src/versionsrv/mapversions.h new file mode 100644 index 000000000..3890599a6 --- /dev/null +++ b/src/versionsrv/mapversions.h @@ -0,0 +1,30 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef VERSIONSRV_MAPVERSIONS_H +#define VERSIONSRV_MAPVERSIONS_H + +static const CMapVersion s_aMapVersionList[] = { + /* 0.7.1, 0.7.2, 0.7.3 */ + {"ctf5", {0x3a, 0x16, 0x94, 0xa7}, {0x00, 0x00, 0x28, 0x0a}, {0x86, 0x92, 0xf4, 0xf9, 0x12, 0x39, 0xb2, 0x98, 0xb6, 0xec, 0xad, 0xb4, 0x70, 0x0d, 0x1a, 0x7a, 0x7f, 0x16, 0x67, 0x42, 0xe3, 0x86, 0x4d, 0x80, 0x26, 0xa4, 0x1c, 0x1d, 0x43, 0xe6, 0x4a, 0x42}}, + {"dm7", {0xa0, 0x09, 0x29, 0x06}, {0x00, 0x00, 0x2a, 0x9e}, {0x8b, 0xde, 0xd9, 0x26, 0xf1, 0x2c, 0xa6, 0xd2, 0x45, 0xa3, 0x95, 0xb4, 0x83, 0x7e, 0xfc, 0x09, 0xd2, 0x5b, 0x5b, 0x0c, 0x72, 0x9d, 0x91, 0x4c, 0xe3, 0x35, 0x0c, 0xee, 0x5b, 0x13, 0x3e, 0x91}}, + /* 0.7.4, 0.7.5 */ + {"ctf1", {0x22, 0xbf, 0x58, 0xcc}, {0x00, 0x00, 0x16, 0x63}, {0x3b, 0x13, 0x4e, 0x3f, 0x6a, 0x69, 0x8e, 0x1f, 0x2e, 0x6a, 0x2f, 0x46, 0xa4, 0xa5, 0x05, 0x24, 0x6f, 0xcf, 0x64, 0xe7, 0x73, 0x0a, 0x8a, 0xd5, 0x49, 0x2f, 0x5b, 0x93, 0xe1, 0x29, 0x69, 0xc6}}, + {"ctf2", {0x4a, 0x5e, 0xe3, 0x26}, {0x00, 0x00, 0x5f, 0x78}, {0xd9, 0xff, 0x8e, 0x31, 0x85, 0x6f, 0x75, 0xd2, 0xf9, 0x73, 0xd8, 0x07, 0x36, 0x45, 0xa9, 0xb5, 0x09, 0x7e, 0x54, 0x72, 0xd1, 0x62, 0x7b, 0x29, 0x60, 0x66, 0x42, 0xd5, 0xfc, 0x62, 0x1f, 0x6d}}, + {"ctf3", {0xa3, 0x73, 0x9d, 0x41}, {0x00, 0x00, 0x17, 0x0f}, {0xd2, 0x14, 0x6f, 0xa3, 0x73, 0x11, 0x9c, 0x78, 0xdc, 0x46, 0x7e, 0x98, 0x78, 0x0a, 0x73, 0xf0, 0xbb, 0x55, 0x45, 0x43, 0xf2, 0xf6, 0x84, 0x70, 0x3c, 0xe8, 0x3a, 0x8d, 0x6d, 0x06, 0x43, 0xff}}, + {"ctf4", {0xbe, 0x7c, 0x4d, 0xb9}, {0x00, 0x00, 0x2e, 0xfe}, {0xdc, 0x01, 0xc0, 0x70, 0x6f, 0xf6, 0x25, 0x88, 0x1a, 0xa5, 0x8c, 0x7d, 0xf3, 0xde, 0xbd, 0x2f, 0x9e, 0x69, 0x2c, 0x83, 0xec, 0xf9, 0xe7, 0x9c, 0x5b, 0x55, 0xbf, 0x8a, 0x2f, 0x83, 0x7c, 0x4b}}, + {"ctf5", {0x20, 0xb9, 0x79, 0x05}, {0x00, 0x00, 0x28, 0x34}, {0xa3, 0x5d, 0xdd, 0x0b, 0xe1, 0x27, 0x9a, 0x6f, 0x3a, 0xc4, 0xe2, 0xc5, 0xe2, 0x9c, 0xa8, 0xda, 0x6b, 0x03, 0xf5, 0x34, 0x7c, 0x5c, 0x44, 0x03, 0x24, 0x84, 0x55, 0x31, 0x81, 0xae, 0x80, 0xc0}}, + {"ctf6", {0x28, 0xc8, 0x43, 0x51}, {0x00, 0x00, 0x69, 0x2f}, {0x1c, 0xe6, 0x18, 0x8e, 0x68, 0xaa, 0xf1, 0xf7, 0xe3, 0xaa, 0xdf, 0x27, 0x8a, 0xb4, 0x4d, 0x8d, 0x9a, 0x02, 0x3f, 0xec, 0xa7, 0x7c, 0xc7, 0x1a, 0xc8, 0xb5, 0x54, 0xc8, 0xfc, 0x8b, 0x3b, 0x63}}, + {"ctf7", {0xec, 0x97, 0xbf, 0x07}, {0x00, 0x00, 0x19, 0x36}, {0x6e, 0x74, 0x9e, 0x6b, 0xf4, 0x01, 0xe5, 0xd3, 0xe2, 0xcb, 0x9d, 0x95, 0x43, 0xb5, 0x25, 0x34, 0x70, 0xfc, 0x00, 0xdd, 0x42, 0xe0, 0x96, 0xa4, 0x8f, 0x47, 0x19, 0xba, 0x1f, 0xcb, 0x8d, 0xe2}}, + {"ctf8", {0x68, 0xe5, 0x43, 0xd2}, {0x00, 0x00, 0x3e, 0xdb}, {0x78, 0x04, 0x36, 0x19, 0x30, 0xb6, 0xee, 0x50, 0xf5, 0x9b, 0xfe, 0x49, 0xbf, 0x9d, 0xa3, 0xb9, 0x01, 0xed, 0x01, 0x47, 0xa5, 0xf2, 0xec, 0xae, 0x25, 0xb2, 0xa4, 0x17, 0xac, 0x95, 0x5f, 0x01}}, + {"dm1", {0x64, 0x54, 0x88, 0x18}, {0x00, 0x00, 0x1a, 0x89}, {0x49, 0x1a, 0xf1, 0x7a, 0x51, 0x02, 0x14, 0x50, 0x62, 0x70, 0x90, 0x4f, 0x14, 0x7a, 0x4c, 0x30, 0xae, 0x0a, 0x85, 0xb9, 0x1b, 0xb8, 0x54, 0x39, 0x5b, 0xef, 0x8c, 0x39, 0x7f, 0xc0, 0x78, 0xc3}}, + {"dm2", {0x05, 0x4b, 0x12, 0x59}, {0x00, 0x00, 0x25, 0x81}, {0xfd, 0x97, 0x36, 0x6e, 0xed, 0xd8, 0x9c, 0x25, 0x4d, 0xb4, 0x64, 0xbc, 0xd3, 0xce, 0x35, 0x5a, 0x84, 0xef, 0xb7, 0xa8, 0x06, 0x34, 0x6b, 0x08, 0x17, 0x1b, 0x7e, 0x49, 0x42, 0xcb, 0x69, 0x64}}, + {"dm3", {0x77, 0x52, 0x3f, 0x3e}, {0x00, 0x01, 0x28, 0xb5}, {0x4d, 0x18, 0x05, 0xbd, 0xa0, 0xf4, 0x82, 0xf1, 0x88, 0x2f, 0x41, 0x00, 0xd1, 0xf2, 0x1a, 0xe9, 0xf4, 0x38, 0xcc, 0x2c, 0x74, 0xa7, 0x1a, 0x24, 0x22, 0x7e, 0xa8, 0x1e, 0x87, 0x51, 0xe1, 0x93}}, + {"dm6", {0x47, 0x4d, 0xa2, 0x35}, {0x00, 0x00, 0x1e, 0x95}, {0x09, 0x64, 0xbc, 0x24, 0xe7, 0xe6, 0xce, 0x7d, 0x1b, 0xca, 0x5c, 0x06, 0x21, 0x64, 0xa9, 0xba, 0xa3, 0xd3, 0x7c, 0x83, 0x4e, 0x0a, 0x83, 0x94, 0xf0, 0x7b, 0x2e, 0xe3, 0x71, 0x94, 0xf0, 0x8b}}, + {"dm7", {0xce, 0x14, 0x84, 0xea}, {0x00, 0x00, 0x25, 0xd5}, {0xbf, 0x98, 0x2d, 0x36, 0x43, 0x0d, 0xab, 0x51, 0x5a, 0xac, 0xb1, 0x6c, 0x08, 0x59, 0x0a, 0xeb, 0xcb, 0x99, 0x17, 0x6e, 0x25, 0x36, 0xff, 0x67, 0x48, 0xf9, 0x75, 0x3f, 0x1b, 0xab, 0xca, 0x6d}}, + {"dm8", {0x18, 0x39, 0x6d, 0x44}, {0x00, 0x01, 0x12, 0x9d}, {0x65, 0x0a, 0x71, 0xa2, 0x0c, 0x54, 0x73, 0x32, 0x9e, 0x2c, 0x5d, 0xca, 0xcf, 0x66, 0x00, 0xf5, 0x41, 0xa6, 0xc9, 0x5a, 0xec, 0xc7, 0x45, 0x77, 0x48, 0x8e, 0x21, 0xae, 0x37, 0xc7, 0x12, 0x91}}, + {"dm9", {0x51, 0x64, 0x9e, 0x61}, {0x00, 0x00, 0x21, 0x8b}, {0x7e, 0x05, 0xc1, 0x57, 0x81, 0x11, 0x86, 0xca, 0x6e, 0x41, 0xb3, 0x36, 0x60, 0x65, 0x9b, 0xc3, 0x1f, 0x2f, 0xfb, 0xed, 0xf1, 0xe6, 0x21, 0xf6, 0x17, 0xdb, 0xae, 0x9d, 0x14, 0x4f, 0x3a, 0x83}}, + {"lms1", {0xb2, 0x71, 0x4a, 0xde}, {0x00, 0x00, 0x2d, 0x33}, {0x97, 0x8d, 0x27, 0xa5, 0x69, 0x6a, 0x09, 0x9f, 0xfd, 0xd3, 0x55, 0x96, 0x93, 0x0d, 0x49, 0xf6, 0x28, 0xf8, 0xe7, 0x0a, 0x3a, 0x76, 0xc4, 0x82, 0x9f, 0x33, 0x65, 0x04, 0x49, 0x1e, 0xdc, 0x1f}}, +}; +static const int s_NumMapVersionItems = sizeof(s_aMapVersionList) / sizeof(CMapVersion); + +#endif diff --git a/src/versionsrv/versionsrv.cpp b/src/versionsrv/versionsrv.cpp new file mode 100644 index 000000000..356db0e85 --- /dev/null +++ b/src/versionsrv/versionsrv.cpp @@ -0,0 +1,171 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include +#include + +#include +#include +#include +#include + +#include + +#include + +#include "versionsrv.h" +#include "mapversions.h" + +enum +{ + MAX_MAPS_PER_PACKET = 48, + MAX_PACKETS = 16, + MAX_MAPS = MAX_MAPS_PER_PACKET * MAX_PACKETS, +}; + +struct CMapversionPacketData +{ + int m_Size; + struct + { + unsigned char m_aHeader[sizeof(VERSIONSRV_MAPLIST)]; + CMapVersion m_aMaplist[MAX_MAPS_PER_PACKET]; + } m_Data; +}; + +static CNetClient s_NetClient; + +static unsigned char s_aVersionPacket[sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)]; +static CMapversionPacketData s_aMapversionPackets[MAX_PACKETS]; +static int s_NumMapversionPackets = 0; + +static void BuildVersionPacket() +{ + mem_copy(s_aVersionPacket, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)); + mem_copy(s_aVersionPacket + sizeof(VERSIONSRV_VERSION), GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION)); +} + +static void BuildMapversionPacket() +{ + dbg_assert(s_NumMapVersionItems <= MAX_MAPS, "too many maps"); + const CMapVersion *pCurrent = &s_aMapVersionList[0]; + int MapsLeft = s_NumMapVersionItems; + s_NumMapversionPackets = 0; + while(MapsLeft > 0 && s_NumMapversionPackets < MAX_PACKETS) + { + const int Chunk = minimum(MapsLeft, MAX_MAPS_PER_PACKET); + MapsLeft -= Chunk; + + // copy header + mem_copy(s_aMapversionPackets[s_NumMapversionPackets].m_Data.m_aHeader, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)); + + // copy map versions + for(int i = 0; i < Chunk; i++) + { + s_aMapversionPackets[s_NumMapversionPackets].m_Data.m_aMaplist[i] = *pCurrent; + pCurrent++; + } + + s_aMapversionPackets[s_NumMapversionPackets].m_Size = sizeof(VERSIONSRV_MAPLIST) + sizeof(CMapVersion) * Chunk; + + s_NumMapversionPackets++; + } +} + +static void SendVersion(NETADDR *pAddr, TOKEN ResponseToken) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = *pAddr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_pData = s_aVersionPacket; + Packet.m_DataSize = sizeof(s_aVersionPacket); + s_NetClient.Send(&Packet, ResponseToken); +} + +static void SendMapversions(NETADDR *pAddr, TOKEN ResponseToken) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = *pAddr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + + for(int i = 0; i < s_NumMapversionPackets; i++) + { + Packet.m_DataSize = s_aMapversionPackets[i].m_Size; + Packet.m_pData = &s_aMapversionPackets[i].m_Data; + s_NetClient.Send(&Packet, ResponseToken); + } +} + +int main(int argc, const char **argv) +{ + dbg_logger_stdout(); + cmdline_fix(&argc, &argv); + + const int FlagMask = 0; + IKernel *pKernel = IKernel::Create(); + IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv); + IConfigManager *pConfigManager = CreateConfigManager(); + IConsole *pConsole = CreateConsole(FlagMask); + + bool RegisterFail = !pKernel->RegisterInterface(pStorage); + RegisterFail |= !pKernel->RegisterInterface(pConsole); + RegisterFail |= !pKernel->RegisterInterface(pConfigManager); + if(RegisterFail) + return -1; + + pConfigManager->Init(FlagMask); + pConsole->Init(); + + if(secure_random_init() != 0) + { + dbg_msg("versionsrv", "could not initialize secure RNG"); + return -1; + } + + NETADDR BindAddr; + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = VERSIONSRV_PORT; + if(!s_NetClient.Open(BindAddr, pConfigManager->Values(), pConsole, 0, 0)) + { + dbg_msg("versionsrv", "could not start network"); + return -1; + } + + dbg_msg("versionsrv", "building packets"); + + BuildVersionPacket(); + BuildMapversionPacket(); + + dbg_msg("versionsrv", "started"); + + while(true) + { + s_NetClient.Update(); + + // process packets + CNetChunk Packet; + TOKEN ResponseToken; + while(s_NetClient.Recv(&Packet, &ResponseToken)) + { + if(Packet.m_DataSize == sizeof(VERSIONSRV_GETVERSION) + && mem_comp(Packet.m_pData, VERSIONSRV_GETVERSION, sizeof(VERSIONSRV_GETVERSION)) == 0) + { + SendVersion(&Packet.m_Address, ResponseToken); + } + + if(Packet.m_DataSize == sizeof(VERSIONSRV_GETMAPLIST) + && mem_comp(Packet.m_pData, VERSIONSRV_GETMAPLIST, sizeof(VERSIONSRV_GETMAPLIST)) == 0) + { + SendMapversions(&Packet.m_Address, ResponseToken); + } + } + + // be nice to the CPU + thread_sleep(1); + } + + cmdline_free(argc, argv); + return 0; +} diff --git a/src/versionsrv/versionsrv.h b/src/versionsrv/versionsrv.h new file mode 100644 index 000000000..91c02e5ab --- /dev/null +++ b/src/versionsrv/versionsrv.h @@ -0,0 +1,24 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef VERSIONSRV_VERSIONSRV_H +#define VERSIONSRV_VERSIONSRV_H + +#include + +static const int VERSIONSRV_PORT = 8285; + +struct CMapVersion +{ + char m_aName[8]; + unsigned char m_aCrc[4]; + unsigned char m_aSize[4]; + unsigned char m_aSha256[SHA256_DIGEST_LENGTH]; +}; + +static const unsigned char VERSIONSRV_GETVERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 'g'}; +static const unsigned char VERSIONSRV_VERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 's'}; + +static const unsigned char VERSIONSRV_GETMAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 'g'}; +static const unsigned char VERSIONSRV_MAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 's'}; + +#endif diff --git a/storage.cfg b/storage.cfg new file mode 100644 index 000000000..5df0e1216 --- /dev/null +++ b/storage.cfg @@ -0,0 +1,34 @@ +#### +# This specifies where and in which order Teeworlds looks +# for its data (sounds, skins, ...). The search goes top +# down which means the first path has the highest priority. +# Furthermore the top entry also defines the save path where +# all data (settings.cfg, screenshots, ...) are stored. +# There are 3 special paths available: +# $USERDIR +# - ~/.appname on UNIX based systems +# - ~/Library/Applications Support/appname on Mac OS X +# - %APPDATA%/Appname on Windows based systems +# $DATADIR +# - the 'data' directory which is part of an official +# release +# $CURRENTDIR +# - current working directory +# $APPDIR +# - usable path provided by argv[0] +# +# +# The default file has the following entries: +# add_path $USERDIR +# add_path $DATADIR +# add_path $CURRENTDIR +# +# A customised one could look like this: +# add_path user +# add_path mods/mymod +#### + +add_path $USERDIR +add_path $DATADIR +add_path $CURRENTDIR +add_path $APPDIR